我正在尝试让一列从时间单位列返回一周数小时的总和。但是,它只返回一个空值,我不确定为什么。有人可以帮忙吗?提前谢谢!
SELECT
[Employee Name],
[Week1] = ISNULL(SUM(CASE WHEN tdate BETWEEN DATEADD(Week,-3,Timesheetdate) AND DATEADD(DAY,-1,DATEADD(WEEK,-2,Timesheetdate)) THEN (Units) END),0 )
[Week2] = ISNULL(SUM(CASE WHEN tdate BETWEEN DATEADD(Week,-2,Timesheetdate) AND DATEADD(DAY,-1,DATEADD(WEEK,-1,Timesheetdate)) THEN (Units) END),0 )
From #Temp
LEFT JOIN TransTable ON TranTable.trankey = Timesheet.tkey
Group By
EmployeeName,
tdate,
tunits,
timesheetdate
答案 0 :(得分:1)
DROP TABLE #Temp
CREATE TABLE #Temp ( [EmployeeName] varchar(100), Timesheetdate datetime , Units int , tdate datetime)
insert into #Temp values ( 1, '2015-03-02',1,'2015-03-02')
insert into #Temp values ( 1, '2015-02-02',2,'2015-02-02')
insert into #Temp values ( 1, '2015-02-02',3,'2015-02-02')
insert into #Temp values ( 1, '2015-02-27',4,'2015-02-02')
insert into #Temp values ( 1, '2015-03-24',5,'2015-02-02')
insert into #Temp values ( 1, '2015-03-02',1,'2015-02-15')
insert into #Temp values ( 1, '2015-02-02',2,'2015-02-17')
insert into #Temp values ( 1, '2015-02-02',3,'2015-02-18')
insert into #Temp values ( 1, '2015-02-27',4,'2015-02-20')
insert into #Temp values ( 1, '2015-03-24',5,'2015-02-14')
insert into #Temp values ( 1, '2015-03-02',1,'2015-02-28')
insert into #Temp values ( 1, '2015-02-02',2,'2015-02-27')
insert into #Temp values ( 1, '2015-02-02',3,'2015-02-26')
insert into #Temp values ( 1, '2015-02-27',4,'2015-02-25')
insert into #Temp values ( 1, '2015-03-24',5,'2015-02-24')
insert into #Temp values ( 1, '2015-03-02',1,'2015-02-21')
insert into #Temp values ( 1, '2015-02-02',2,'2015-02-20')
insert into #Temp values ( 1, '2015-02-02',3,'2015-02-18')
insert into #Temp values ( 1, '2015-02-27',4,'2015-02-20')
insert into #Temp values ( 1, '2015-03-24',5,'2015-02-18')
SELECT
EmployeeName,
[Week1] = ISNULL(SUM(CASE WHEN tdate BETWEEN DATEADD(Week,-3,Timesheetdate) AND DATEADD(DAY,-1,DATEADD(WEEK,-2,Timesheetdate)) THEN (Units) ELSE 0 END),0 ),
[Week2] = ISNULL(SUM(CASE WHEN tdate BETWEEN DATEADD(Week,-2,Timesheetdate) AND DATEADD(DAY,-1,DATEADD(WEEK,-1,Timesheetdate)) THEN (Units) ELSE 0 END),0 )
From #Temp
GROUP BY EmployeeName
它似乎工作得很好,我所做的只是我已经添加了ELSE 0(这不是必要的,因为没有它也可以正常工作)。
更好地了解您的日期。也许它应该返回null