在过滤数据时,我遇到了一年中的财务周以及周开始日期。
这里是一个示例数据,其中在一个星期的开始日期中,一年中有2个不同的财政周。
SELECT
WEEK_COMMENCING
,FISCAL_WEEK_OF_YEAR
,[issue_date]
,sum([issue_value])
FROM [DM_Pharmacy].[dbo].[daily_issue_summary]
JOIN [DM_Common].[dbo].[REFERENCE_DATE_PROFILE]
ON issue_date = DATE
WHERE [issue_date] >= '2017-03-30'
AND [issue_date] <= '2018-11-22'
AND FISCAL_WEEK_OF_YEAR IN ('01', '53')
GROUP BY WEEK_COMMENCING
,FISCAL_WEEK_OF_YEAR
,[issue_date],[issue_value]
ORDER BY [issue_date] ASC
+-------------------------+---------------------+------------+-------------+
| WEEK_COMMENCING | FISCAL_WEEK_OF_YEAR | issue_date | issue_value |
+-------------------------+---------------------+------------+-------------+
| 2017-03-27 00:00:00.000 | 53 | 2017-03-30 | 10 |
| 2017-03-27 00:00:00.000 | 53 | 2017-03-31 | 15 |
| 2017-03-27 00:00:00.000 | 01 | 2017-04-01 | 4 |
| 2017-03-27 00:00:00.000 | 01 | 2017-04-02 | 6 |
| 2018-03-26 00:00:00.000 | 53 | 2018-03-26 | 2 |
| 2018-03-26 00:00:00.000 | 53 | 2018-03-27 | 2 |
| 2018-03-26 00:00:00.000 | 53 | 2018-03-28 | 2 |
| 2018-03-26 00:00:00.000 | 53 | 2018-03-29 | 2 |
| 2018-03-26 00:00:00.000 | 53 | 2018-03-30 | 2 |
| 2018-03-26 00:00:00.000 | 53 | 2018-03-31 | 2 |
| 2018-03-26 00:00:00.000 | 01 | 2018-04-01 | 2 |
+-------------------------+---------------------+------------+-------------+
这是我的简化案例声明
我正在努力实现:
如果[WEEK_COMMENCING]在 @PreviousYear_Start 或 @CurrentYear_Start
中有2个FISCAL_WEEK_OF_YEAR然后仅在FISCAL_WEEK_OF_YEAR = 01时求和,而忽略FISCAL_WEEK_OF_YEAR = 53
Declare @PreviousYear_Start DATE = '2017-03-27';
Declare @PreviousYear_End DATE = '2018-03-26';
Declare @CurrentYear_Start DATE = '2018-03-26';
Declare @CurrentYear_End DATE = '2018-09-30';
SELECT TOP 10
[drug_name]
,SUM(CASE
WHEN [WEEK_COMMENCING] >= @PreviousYear_Start AND
[WEEK_COMMENCING] <= @PreviousYear_End THEN [issue_value]
END) AS prev_yr
,SUM(CASE
WHEN [WEEK_COMMENCING] >= @CurrentYear_Start AND
[WEEK_COMMENCING] <= @CurrentYear_End THEN [issue_value]
END) AS this_yr
FROM [DM_Pharmacy].[dbo].[weekly_issue_summary]
LEFT JOIN [costcentre_groups_staging]
ON [weekly_issue_summary].costcentre = [costcentre_groups_staging].costcentre
GROUP BY [drug_name]
ORDER BY SUM(CASE
WHEN [WEEK_COMMENCING] >= @CurrentYear_Start AND
[WEEK_COMMENCING] <= @CurrentYear_End THEN [issue_value]
END) DESC