sql - DateDiff By Day of Week Count Does Not Match Actual Count from Paper Calendar
问题描述
I have a query that groups by day of the week basis:
SELECT DATENAME(DW,rct.rpt_date) [Day of The Week]
,DATEDIFF(day,CAST(@date_from as DATE),CAST(@date_to AS DATE) [Number]
,COUNT(DISTINCT rct.rpt_date) as [Occurrence / Active]
FROM receipt_summary rct
WHERE rct.rpt_date between CAST(@date_from as DATE) and CAST(@date_to AS DATE)
AND rct.bus_id = 10
GROUP BY DATENAME(DW,rct.rpt_date)
ORDER BY CASE DATENAME(DW,rct.rpt_date)
WHEN 'SUNDAY' THEN 1
WHEN 'MONDAY' THEN 2
WHEN 'TUESDAY' THEN 3
WHEN 'WEDNESDAY' THEN 4
WHEN 'THURSDAY' THEN 5
WHEN 'FRIDAY' THEN 6
WHEN 'SATURDAY' THEN 7 END
When I used DATEDIFF(wk,@dateFrom,@dateTo) as one the columns, the count in Number column is same across the seven days. It doesn't match the number I aimed to get when count comparing with using a paper calendar.
For example, between 1 December 2019 and 12 March 2020, I would expect to see 15 times of Sundays to Thursdays, while Fridays and Saturdays should show 14 times. The Inactive column is naturally a subtraction of Number - Occurrences. Per the problem above, Sunday - Thursday shows 14.
This screenshot is what I am hoping to achieve:
Can anyone help on this? Where exactly did I miss out on?
Note: For grouping by Day of the Month, I am aware that it is similar in structure except for replacing DATENAME(DW,date) with DATENAME(D,rct.rpt_date) + CASE WHEN DAY IN (1,21,31) Then ...
etc, but how different will it be the handling in the DATEDIFF portion?
UPDATE The updated screenshot shows the current and expected results:
This is a calendar from December 2019 to March 2020. Drawn in boxes are number of Sundays, Mondays and so forth from (date from) to 12 March 2020 (date to).
解决方案
推荐阅读
- reactjs - 有没有办法在 React 开发工具中获取页面上使用的组件的枚举?
- flutter - 如何在颤动中将文本+图标作为步进器的步骤标题
- video - SVT-AV1:编码后的视频搜索在任何视频播放器(甚至 HTML5)中都非常糟糕
- android - Android,Kotlin:我怎样才能只允许我的视图寻呼机在需要时向左滑动
- javascript - 如何在Vue Js中循环遍历Json数组中的子数组?
- python - 芹菜错误 Windows 上无法识别的错误
- c++ - 在 Visual Studio 19 中无法识别 ofstream 和 ifstream 的错误
- python - 如何在 RGB 图像上应用 DCT 隐写术?
- html - Bootstrap 卡边框消失,网格不工作
- r - 如何根据用户的权限在 Shiny 中显示不同的标题选项卡?