有一个员工表,每个人每天重新订购一个条目。
我创建了这个查询并且它有效,但是不是上周工作的总小时数,而是应该是员工从开始时间开始的总小时数的总和。
有人能帮忙吗?我搞不清楚了。谢谢。
SELECT SSN, firstname, Lastname, SUM(CAST(Hours as float)) AS HourstoDate
FROM Employees
WHERE CAST(Scheduled as datetime) >= DateAdd( d, DateDiff( d, 0, GetDate()-5 ), 0 )
GROUP BY SSN, Lastname, FirstName
SSN FirstName LastName Scheduled Hours
1234 Jane Doe Monday 9/26 10
1234 Jane Doe Tuesday 9/27 10
自从她本周工作以来,应该拉简的入学,但是小时需要1525,而不是她本周工作的20。
答案 0 :(得分:0)
查询无效,因为您在同一个表中将两个搜索合并为一个。您无法在特定日期之后搜索记录,并且同时从一开始就检索所有记录。
在这些情况下,我的方法是自己加入表格。理想情况下它应该是这样的:
select
z.ssn
, z.firstname
, z.lastname
, sum ( cast ( eo.hours as float ) ) as hourstodate
from (
select distinct
ei.ssn
, ei.firstname
, ei.lastname
from
employees ei
where
cast ( ei.scheduled as datetime ) > dateadd ( ei.d , datediff ( ei.d , 0 , getdate() - 5 ) , 0 )
) z
join employees eo on ( z.ssn = eo.ssn and z.firstname = eo.firstname and z.lastname = eo.lastname )
group by
z.ssn
, z.lastname
, z.firstdate
我无法尝试,所以我不能保证它会起作用。如果它返回错误,请随意添加注释。
编辑:错误
答案 1 :(得分:0)
你可以改变你的过滤器,使它总计所有小时首先,然后确保满足(使用having
子句的“本周工作”条件),如下所示:
SELECT SSN, firstname, Lastname, SUM(CAST(Hours as float)) AS HourstoDate, max(case when CAST(Scheduled as datetime) >= DateAdd( d, DateDiff( d, 0, GetDate()-5 ), 0 ) then 1 else 0 end) as worked_this_week
FROM Employees
GROUP BY SSN, Lastname, FirstName
HAVING max(case when CAST(Scheduled as datetime) >= DateAdd( d, DateDiff( d, 0, GetDate()-5 ), 0 ) then 1 else 0 end) = 1