我遇到了以下问题。如何按照每周累计计数的方式对以下数据进行分组。
+---------------------+-----+
| data |count|
+---------------------+-----+
| 2012-08-01 00:00:00 | 4 |
| 2012-08-02 00:00:00 | 5 |
| 2012-08-03 00:00:00 | 6 |
| 2012-08-04 00:00:00 | 6 |
| 2012-08-05 00:00:00 | 8 |
| 2012-08-06 00:00:00 | 6 |
| 2012-08-07 00:00:00 | 8 |
| 2012-08-08 00:00:00 | 6 |
| 2012-08-09 00:00:00 | 2 |
| 2012-08-10 00:00:00 | 0 |
| 2012-08-11 00:00:00 | 5 |
| 2012-08-12 00:00:00 | 4 |
| 2012-08-13 00:00:00 | 4 |
| 2012-08-14 00:00:00 | 0 |
+---------------------+-----+
本周应以周日 - 周六格式计算.....
答案 0 :(得分:2)
从日期减去星期几(假设没有时间部分)然后按其分组:
select
dateadd(day, -(DATEPART(weekday, data) + @@DATEFIRST + 4) % 7, data)
,sum([count])
from tab
group by
dateadd(day, -(DATEPART(weekday, data) + @@DATEFIRST + 4) % 7, data)
(DATEPART(weekday, data) + @@DATEFIRST + 4) % 7
返回0(=星期日)和6(星期六)之间的数字,与@@DATEFIRST
设置无关。
请参阅Fiddle