我目前仍然遇到这个问题。假设我有以下日常数据
+-------------------------+-----+----+
| Date | C1 | C2 |
+-------------------------+-----+----+
| 2012-08-01 00:00:00.000 | 44 | 44 |
| 2012-08-02 00:00:00.000 | 51 | 49 |
| 2012-08-03 00:00:00.000 | 60 | 59 |
| 2012-08-04 00:00:00.000 | 68 | 67 |
| 2012-08-05 00:00:00.000 | 82 | 78 |
| 2012-08-06 00:00:00.000 | 62 | 59 |
| 2012-08-07 00:00:00.000 | 58 | 53 |
| 2012-08-08 00:00:00.000 | 69 | 65 |
| 2012-08-09 00:00:00.000 | 82 | 72 |
| 2012-08-10 00:00:00.000 | 70 | 68 |
| 2012-08-11 00:00:00.000 | 75 | 71 |
| 2012-08-12 00:00:00.000 | 64 | 64 |
| 2012-08-13 00:00:00.000 | 74 | 69 |
| 2012-08-14 00:00:00.000 | 60 | 56 |
| 2012-08-15 00:00:00.000 | 66 | 60 |
| 2012-08-16 00:00:00.000 | 57 | 51 |
| 2012-08-17 00:00:00.000 | 52 | 49 |
+-------------------------+-----+----+
我如何将它分组,以便每周总结C1和C2? 预期的输出应该是
+---------------------------+------+----+
| Date | C1 | C2 |
+---------------------------+------+----+
| 2012-08-06 to 2012-12-12 | 480 | 452|
| 2012-08-13 to 2012-08-19 | 430 | 394|
+---------------------------+------+----+
从2012-08-06开始,因为周期应该是周一到周日。 我已经尝试了大约一个小时的谷歌搜索,似乎没有结果符合我的问题,我希望有人可以帮助我。
谢谢!
答案 0 :(得分:6)
试试这个:
SET DATEFIRST 1会将您的周开始设置为星期一
SET DATEFIRST 1
SELECT CAST(MIN( [DATE]) AS VARCHAR(20))+' TO '+CAST (MAX([DATE]) AS VARCHAR(20)) AS DATE,
SUM(C1) AS GRU,
SUM(C2) AS C1
FROM YOUR_TABLE
GROUP BY DATEPART(WEEK,[DATE])
HAVING COUNT(DISTINCT[DATE])=7
SET DATEFIRST 7
答案 1 :(得分:3)
也许这样的事情(记得接受答案)
declare @t table(Date datetime, C1 int, C2 int)
insert @t values('2012-08-01',44,44)
insert @t values('2012-08-02',51,49)
insert @t values('2012-08-03',60,59)
insert @t values('2012-08-04',68,67)
insert @t values('2012-08-05',82,78)
insert @t values('2012-08-06',62,59)
insert @t values('2012-08-07',58,53)
insert @t values('2012-08-08',69,65)
insert @t values('2012-08-09',82,72)
insert @t values('2012-08-10',70,68)
insert @t values('2012-08-11',75,71)
insert @t values('2012-08-12',64,64)
insert @t values('2012-08-13',74,69)
insert @t values('2012-08-14',60,56)
insert @t values('2012-08-15',66,60)
insert @t values('2012-08-16',57,51)
insert @t values('2012-08-17',52,49)
select
convert(varchar(10), dateadd(week, datediff(week, 0, date-1),0), 120)+' to '+
convert(varchar(10), max(dateadd(week, datediff(week, 0,date-1),6)), 120) Date,
sum(C1) GRU, sum(C2) C1
from @t
group by dateadd(week, datediff(week, 0, date-1),0)
having datediff(day, 0, min(date)) %7 = 0