我有一个查询,我正在运行以从数据库中拉出数小时。我正在使用2个表Employee_TB
和Payroll_Hours_TB
。查询正在运行,但是它没有显示“0”小时的活跃员工。我希望查询显示那些活跃Employee_Tb.Active_Flag = 1
的员工有小时,0小时的日期范围。
SELECT
REPLACE(REPLACE(Employee_Tb.First_Name, '.', ''), ' ', '') AS FirstName,
REPLACE(REPLACE(Employee_Tb.Last_Name, '.', ''), ' ', '') AS LastName,
Employee_Tb.Home_Store_Id, Employee_Tb.Payroll_Id,
SUM(Payroll_Hours_Tb.Hours_Worked) AS RegHours
FROM Employee_Tb
LEFT OUTER JOIN Payroll_Hours_Tb ON Employee_Tb.Employee_Id = Payroll_Hours_Tb.Employee_Id
WHERE (Payroll_Hours_Tb.Work_Date BETWEEN @startdate AND @enddate)
AND (Employee_Tb.Active_Flag = 1)
GROUP BY Employee_Tb.Payroll_Id, Employee_Tb.First_Name, Employee_Tb.Last_Name, Employee_Tb.Home_Store_Id
答案 0 :(得分:5)
将以下条件从where
子句移到on
子句:
(Payroll_Hours_Tb.Work_Date BETWEEN @startdate AND @enddate)
......就像这样:
-- simplified column list for demonstration
select
e.Employee_Id
,coalesce(sum(h.Hours_Worked), 0) as RegHours
from Employee_Tb as e
left join Payroll_Hours_Tb as h
on e.Employee_Id = h.Employee_Id
and h.Work_Date between @startdate and @enddate
where e.Active_Flag = 1
group by e.Employee_Id
否则,您将在加入后过滤整个
。答案 1 :(得分:0)
是否显示null而不是0?
也许你可以试试像
这样的东西 ISNULL(SUM(Payroll_Hours_Tb.Hours_Worked), 0) AS RegHours