我有一个SQL查询,可以获取员工姓名,家庭商店,工资单ID和工作总时数。以下是查询:
SELECT Employee_Tb.First_Name + ' ' + Employee_Tb.Last_Name AS Name,
Employee_Tb.Home_Store_Id, Employee_Tb.Payroll_Id,
SUM(Payroll_Hours_Tb.Hours_Worked) AS TotalHours
FROM Employee_Tb
INNER JOIN Payroll_Hours_Tb
ON Employee_Tb.Employee_Id = Payroll_Hours_Tb.Employee_Id
WHERE (Payroll_Hours_Tb.Work_Date BETWEEN @startdate AND @enddate)
GROUP BY Employee_Tb.Payroll_Id, Employee_Tb.First_Name, Employee_Tb.Last_Name,
Employee_Tb.Home_Store_Id
ORDER BY Employee_Tb.Home_Store_Id
我希望将总小时数分为"Regular Hours"
和"OT Hours"
正常小时定义为小于" 40"小时。 OT小时定义为大于" 40"
答案 0 :(得分:0)
您应该可以使用CASE
表达式,每个值一个。
而不是SUM(Payroll_Hours_Tb.Hours_Worked)
,您可以这样做:
CASE WHEN SUM(Payroll_Hours_Tb.Hours_Worked) > 40.0
THEN 40.0
ELSE SUM(Payroll_Hours_Tb.Hours_Worked)
END AS RegularHours,
CASE WHEN SUM(Payroll_Hours_Tb.Hours_Worked) > 40.0
THEN SUM(Payroll_Hours_Tb.Hours_Worked) - 40.0
ELSE 0.0
END AS Overtime
第一个CASE
表达式检查小于40的小时数,如果找到,则在正常时间锁定为40,否则使用小时数(因为它小于40)
第二个CASE
表达式检查小于40的小时数,如果找到,则从小时数中减去40,以确定加班时间。
答案 1 :(得分:0)
with cte as
(
SELECT Employee_Tb.First_Name + ' ' + Employee_Tb.Last_Name AS Name,
Employee_Tb.Home_Store_Id, Employee_Tb.Payroll_Id,
SUM(Payroll_Hours_Tb.Hours_Worked) AS TotalHours
FROM Employee_Tb
INNER JOIN Payroll_Hours_Tb
ON Employee_Tb.Employee_Id = Payroll_Hours_Tb.Employee_Id
WHERE (Payroll_Hours_Tb.Work_Date BETWEEN @startdate AND @enddate)
GROUP BY Employee_Tb.Payroll_Id, Employee_Tb.First_Name, Employee_Tb.Last_Name,
Employee_Tb.Home_Store_Id
ORDER BY Employee_Tb.Home_Store_Id
)
SELECT Name, Home_Store_Id, Payroll_Id, TotalHours,
CASE
WHEN TotalHours <= 40 THEN TotalHours
ELSE 40
END AS 'Regular',
CASE
WHEN TotalHours > 40 THEN TotalHours - 40
ELSE 0
END AS 'OT'
FROM cte