如何用" 0"显示结果

时间:2014-07-08 18:27:15

标签: sql sql-server

我有一个查询,我正在运行以从数据库中拉出数小时。我正在使用2个表Employee_TBPayroll_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

2 个答案:

答案 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