在Transact-SQL中按周分组

时间:2016-08-02 22:15:23

标签: sql-server tsql

我试图在7天内计算物品数量,同时仍然能够报告所述七天期间的第一个日期。到目前为止我最接近的是

WITH w (w, n)
AS 
(
    SELECT MIN(CAST(CreatedDate AS DATE)) 
                OVER(   
                        PARTITION BY DATEPART(WEEK, CAST(CreatedDate AS DATE)) 
                        ORDER BY DATEPART(WEEK, CAST(CreatedDate AS DATE))
                    )
            ,COUNT(*)
    FROM dbo.Tbl
    WHERE 
        CreatedDate >= CAST(DATEADD(MONTH,-6,GETDATE()) AS DATE)
    GROUP BY CAST(CreatedDate AS DATE)
)
SELECT w.w AS [Week of], SUM(w.n) AS [Items]
FROM w
GROUP BY w.w
ORDER BY 1 DESC

但遗憾的是,这不适用于今年的第一周或最后一周,如果日期范围包括一年以上,则无效。

有没有办法在七天的时间内分组,同时还能在上述期间获得第一个约会?

1 个答案:

答案 0 :(得分:1)

您可以根据日期值使用以下内容获取周数。您需要在周围添加日期以适应您的情况,但您将始终保证相同的开始和结束日。在这种情况下,一周从星期日开始,到星期六结束:

declare @Date datetime

set @Date = '20160802'

select @Date - DATEPART(dw, @Date) + 1 as FirstDateOfWeek
      ,@Date + (7 - DATEPART(dw, @Date)) as LastDateOfWeek

对于完全无懈可击的解决方案,您可以添加逻辑以检查并使用@@DATEFIRST并相应地分配调整值。

获得周开始值后,您可以在group by

中使用该值
select CreatedDate - DATEPART(dw, @Date) + 1 as FirstDateOfWeek
      ,count(*)
from tbl
group by CreatedDate - DATEPART(dw, @Date) + 1
order by FirstDayOfWeek