我当前的SQL看起来像这样:
Declare @Start datetime;
Declare @End datetime;
set @Start = '2016-04-4';
set @End = '2016-04-10';
Select pr.PR_FIELD03 AS EENo, pr.PR_Name AS EEName, lo.LocationName AS [State], SUM(ts.TotalMins/60) AS Hours, ts.OTFlag from TimeSheets as ts
join BWSPRMSD as pr on ts.EmployeeSSN = pr.PR_SSN
join Locations as lo on ts.LocationID = lo.LocationID
where ts.TransDate >= @start AND ts.TransDate <= @End AND ts.ActiveFlag = 1 AND HolidayFlag = 0 AND VacationFlag = 0
group by pr.PR_FIELD03, pr.PR_Name, lo.LocationName, ts.OTFlag;
已更新
那会给我:
EENo EEName State Hours OTFlag
118 Randy TX 31 1
118 Randy TX 40 0
118 Randy MS 40 0
125 Bill OK 40 0
我需要的是:
EENo EEName Reg Hours O.T. Hours State
118 Randy 40 31 TX
118 Randy 40 0 MS
125 Bill 40 0 OK
您可能会有任何建议。
提前谢谢
更新
我道歉,因为我的原帖不是很清楚。不,我不想只更改列名,如果设置了OTFlag,我需要在同一行上拆分小时数。
顺便说一句,如果linq或Lambda是你的一杯茶。这些答案也会起作用。
答案 0 :(得分:1)
继续进行CTE。我没有仔细检查我的代码,但它应该非常接近!假设您在时间表上有一个名为OTFlag的标志,在输入常规小时时设置为0,在OT小时时设置为1。这样,对于他们所在的每个州,每个员工都有一个条目。
Declare @Start datetime;
Declare @End datetime;
set @Start = '2016-04-4';
set @End = '2016-04-10';
with regHours as (SELECT ts.employeeSSN, CAST(decimal(5,2),SUM(ts.totalMins/60) AS RegHours , lo.locationName as State
FROM TimeSheets ts
join Locations as lo on ts.LocationID = lo.LocationID
where ts.TransDate >= @start
AND ts.TransDate <= @End
AND ts.ActiveFlag = 1
AND ts.OTFlag = 0
AND HolidayFlag = 0
AND VacationFlag = 0
Group BY ts.employeeSSN, lo.locationName)
Select pr.PR_FIELD03 AS EENo
, pr.PR_Name AS EEName
, rh.regHours as 'Regular Hours'
, SUM(ts.TotalMins/60) AS 'O.T. Hours'
, lo.LocationName AS [State]
from TimeSheets as ts
join BWSPRMSD as pr on ts.EmployeeSSN = pr.PR_SSN
join Locations as lo on ts.LocationID = lo.LocationID
join regHours rh ON rh.employeeSSN = ts.employeeSSN AND rh.State = ts.LocationID
where ts.TransDate >= @start
AND ts.TransDate <= @End
AND ts.ActiveFlag = 1
AND HolidayFlag = 0
AND VacationFlag = 0
group by pr.PR_FIELD03, pr.PR_Name, lo.LocationName, rh.RegHours