SQL Group按周日期

时间:2016-04-27 14:49:36

标签: sql-server group-by

我正在尝试按周日期对SQL Server中的订单列表进行分组。使用下面的SQL我得到以下结果:

SELECT cast(datepart(wk, created) [week], count(1) [number of orders]
FROM Orders
GROUP BY datepart(wk, created)

Week - Number of Orders
15   - 305
16   - 285
17   - 428

我想要做的不是显示周数,而是要显示星期开始日期,例如

Week -       Number of Orders
11/04/2016   - 305
18/04/2016   - 285
25/04/2016   - 428

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

这给了我星期一......

SELECT  DATEADD(Week, DATEDIFF(week, 0, created), 0) [week], 
        count(1) [number of orders]
FROM    Orders
GROUP BY DATEADD(Week, DATEDIFF(week, 0, created), 0)

如果上面给你星期一,这应该给你星期天

DATEADD(Week, DATEDIFF(week, 0, created), -1)

答案 1 :(得分:2)

SELECT  DATEADD(day, 1 - DATEPART(weekday, created), CAST(created AS DATE)),
        COUNT(*)
FROM    Orders
GROUP BY
        DATEADD(day, 1 - DATEPART(weekday, created), CAST(created AS DATE))

您可以使用SET DATEFIRST控制周开始日。