diff --git a/README.md b/README.md index 1fe320f..b3c7470 100644 --- a/README.md +++ b/README.md @@ -97,7 +97,7 @@ Usage: `{{ pm_utils.date_from_timestamp('[expression]') }}` #### datediff ([source](macros/multiple_databases/datediff.sql)) -This macro computes the difference between two date, time, or datetime expressions based on the specified `datepart` and returns an integer value. The datepart can be any of the following values: year, quarter, month, week, day, hour, minute, second, millisecond. +This macro computes the difference between two date, time, or datetime expressions based on the specified `datepart` and returns an integer value. The datepart can be any of the following values: year, quarter, month, week, day, hour, minute, second, millisecond. The difference in weeks is calculated for weeks starting on Monday. Usage: `{{ pm_utils.datediff('[datepart]', '[start_date_expression]', '[end_date_expression]') }}` diff --git a/macros/multiple_databases/datediff.sql b/macros/multiple_databases/datediff.sql index 998573a..1a75052 100644 --- a/macros/multiple_databases/datediff.sql +++ b/macros/multiple_databases/datediff.sql @@ -3,7 +3,12 @@ {%- if target.type == 'snowflake' -%} datediff({{ datepart }}, {{ start_date_field }}, {{ end_date_field }}) {%- elif target.type == 'sqlserver' -%} - datediff_big({{ datepart }}, {{ start_date_field }}, {{ end_date_field }}) + {%- if datepart == 'week' -%} + {# To calculate week differences, weeks start by default on Sunday. Change to align with Snowflake (week starts on Monday) #} + datediff_big({{ datepart }}, dateadd(day, -1, {{ start_date_field }}), dateadd(day, -1, {{ end_date_field }})) + {%- else -%} + datediff_big({{ datepart }}, {{ start_date_field }}, {{ end_date_field }}) + {%- endif -%} {%- endif -%} {%- endmacro -%}