From 6eb08cd3a8119d7a5015da01e914e3fa6cf96db8 Mon Sep 17 00:00:00 2001 From: Dennis-UiPath Date: Tue, 3 Oct 2023 10:09:06 +0200 Subject: [PATCH] fix: align datediff in weeks for SQL Server with Snowflake --- README.md | 2 +- macros/multiple_databases/datediff.sql | 7 ++++++- 2 files changed, 7 insertions(+), 2 deletions(-) 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 -%}