如何按周分组?

时间:2014-06-23 09:32:01

标签: sql sql-server tsql

我需要创建一个报告,我需要按周计算UserHits的总和,从特定年份的第一周到最后一周。

如何实现这一目标?

http://sqlfiddle.com/#!6/eb181/1/0

CREATE TABLE UserData
(
DateCreated dateTime2 NOT NULL,
UserHits int NOT NULL
);

insert into UserData
values
('2014-01-01',100),
('2014-01-02',50),
('2014-01-03',20),
('2014-01-20',100),
('2014-01-21',100),
('2014-01-22',70),
('2014-02-02',100),
('2014-02-03',100);

1 个答案:

答案 0 :(得分:5)

select  datepart(wk, DateCreated)
,       sum(UserHits)
from    UserData
group by
        datepart(wk, DateCreated)