我试图将每7天分组到一周但我的问题是第一周的时间总是很多。我的意思是,我们每周工作40小时,但总是第一周的工作时间很远,剩下的几周也没问题。例如:
WeekBeginDate TotalHours
7/6/2015 10
7/13/2015 40
7/20/2015 40
我知道第一周应该是40,但它显示不到40小时。这是我的sql。
Select x.UID,
Convert(VarChar, x.WeekBeginDate, 101) As WeekBeginDate,
x.TOTAL_HOURS
From
(
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 UID = 'mike01'
And DT >= DateAdd(Week, -3, GetDate())
Group By UID, Convert(Int, DateDiff(DD, '1/1/1900', t.DT) / 7)
)x;
答案 0 :(得分:1)
你能使用datepart函数吗?
SELECT DATEPART(WEEK,GETDATE())
**编辑**
我看到你正在尝试做什么。只需将所有日期转换为一周的开头并按其分组。
SELECT UID,
DD - DATEPART(dw,DD) + 1 AS [WeekBeginDate],
SUM(HOURS) AS [HOURS]
FROM dbo.mytable
WHERE UID = 'mike01'
GROUP BY UID, DD - DATEPART(dw,DD) + 1
这是我用来测试它的安装脚本。
CREATE TABLE mytable (
[UID] varchar(100),
DD DATETIME,
[HOURS] DECIMAL(18,2)
)
INSERT INTO dbo.mytable
( UID, DD, HOURS )
VALUES ('mike01', '2015-07-30',1),
('mike01', '2015-07-29',6),
('mike01', '2015-07-23',2),
('mike01', '2015-07-16',3)