在 SQL 中将一周的第一天作为星期日开始

2021-09-10 00:00:00 tsql sql-server-2008 sql-server

我希望我一周的第一天是星期日,但我的代码问题是它总是从星期一开始.

I want my first day of the week to be as Sunday but my issue with my code is that it starts always as Monday.

SELECT 
    UID,
    DATEADD(DD,CONVERT(INT, (DATEDIFF(DD, '1/1/1900', t.DT)/7)) * 7,'1/1/1900') [WeekBeginDate], 
    SUM(HOURS) AS TOTAL_HOURS 
FROM 
    myTable t 
WHERE 
    DT >= DATEADD(WEEK, -6, GetDate()) 
GROUP BY 
    UID, CONVERT(INT, DATEDIFF(DD, '1/1/1900', t.DT)/7)

推荐答案

这应该可以解决问题:

SELECT
  UID,  
  DATEADD(d, -1, DATEDIFF(d, -1, t.DT)/7 * 7) [WeekBeginDate] ,
  SUM(HOURS) AS TOTAL_HOURS 
FROM myTable t 
WHERE DT >= DATEADD(WEEK, -6, GetDate()) 
GROUP BY UID, DATEDIFF(d, -1, t.DT)/7

相关文章