SQL Server: Date truncation for custom time periods

Oracle has the trunc function and PostgreSQL / Redshift have the date_trunc function that allows you to truncate a timestamp to a specific unit of measure like year, quarter, month, week, etc. These functions are handy when rolling up and aggregating data for custom intervals.

If you want a similar function for SQL Server, you can use this macro:

select dateadd({period}, datediff({period}, 0, {field}), 0)

Where {period} is the period of interest like YEAR, QUARTER, MONTH, DAY, HOUR, etc. and {field} is the column of interest.

Examples

Timestamp Interval SQL Result
2017-05-13T01:17:42Z YEAR select dateadd(YEAR, datediff(YEAR, 0, {field}), 0) 2017-01-01T00:00:00Z
2017-05-13T01:17:42Z QUARTER select dateadd(QUARTER, datediff(QUARTER, 0, {field}), 0) 2017-04-01T00:00:00Z
2017-05-13T01:17:42Z MONTH select dateadd(MONTH, datediff(MONTH, 0, {field}), 0) 2017-05-01T00:00:00Z
2017-05-13T01:17:42Z WEEK select dateadd(WEEK, datediff(WEEK, 0, {field}), 0) 2017-05-08T00:00:00Z
2017-05-13T01:17:42Z DAY select dateadd(DAY, datediff(DAY, 0, {field}), 0) 2017-05-13T00:00:00Z
2017-05-13T01:17:42Z HOUR select dateadd(HOUR, datediff(HOUR, 0, {field}), 0) 2017-05-13T01:00:00Z

Silota's SQL Macro for date truncation

Silota makes this super easy with our SQL Macros. For example:

    declare @dt as datetime = '2017-05-13T01:17:42Z';

    select @dt as Original,
        'year' as Period,
        [@dt:year] as Result
    union
    select @dt as Original,
        'quarter' as Period,
        [@dt:quarter] as Result
    union
    select @dt as Original,
        'month' as Period,
        [@dt:month] as Result
    union
    select @dt as Original,
        'week' as Period,
        [@dt:week] as Result
    union
    select @dt as Original,
        'day' as Period,
        [@dt:day] as Result
    union
    select @dt as Original,
        'hour' as Period,
        [@dt:hour] as Result


👋 No fuss, just SQL We are open sourcing everything from the experience working with our agency clients. They spend thousands of dollars to get this level of detailed analysis – which you can now get for free. We send one update every week. Join 400+ data analysts who are leveling up with our recipes. 👊

No spam, ever! Unsubscribe any time. See past emails here.

results matching ""

    No results matching ""