在SQL中按周分组

时间:2017-07-12 14:39:01

标签: sql sql-server

我有一个带有这样输出的SQL查询

7   2017-05-02 00:00:00.000
96  2017-05-15 00:00:00.000
79  2017-05-16 00:00:00.000
310 2017-05-17 00:00:00.000
76  2017-05-18 00:00:00.000
83  2017-05-19 00:00:00.000

我想按周分组。

理想输出

7     Week 1
644   Week 2

如何分组这样的任何帮助将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:2)

假设您可以使用一周的数据库定义:

select datename(year, datecol) + '-' + datename(week, datecol) as yyyyw,
       sum(col) as sumcol
from t
group by datename(year, datecol) + '-' + datename(week, datecol)
order by min(datecol);

答案 1 :(得分:0)

另一个选择

示例

Select SomeValue = sum(SomeValue)
      ,WeekNr=concat('Week ',dense_rank() over (Order By datepart(week,SomeDate)) )
 from YourTable
 Group By year(SomeDate),datepart(week,SomeDate)

<强>返回

SomeValue   WeekNr
7           Week 1
644         Week 2