嗯,我有这个 -
Table DimDate- Date
Table Employee- Id,Name,Points,Date
现在,员工表每天都有积分,除非他们没有来...所以日期没有所有日期条目...我的意思是,例如,在一周内,他有 2 天没有来,员工表有只有 5 行...所以我有这个暗淡日期表,其中包含 2050 年之前的所有日期,我想将其加入并为他没有积分的日期添加零。所以我写了这个查询但不起作用 -
Select E.EmployeeId,D.Date,isNull(E.Points,0) from DimDate D left join Employee E on D.Date between '01-01-2009'and '06-01-2009' where E.EmployeeId=1
上面的查询给出了多个日期,我尝试对日期进行分组,但不起作用。
最佳答案
您可能不想在日期范围上连接两个表,而是在日期上连接。然后按日期范围过滤记录集。示例
Select
E.EmployeeId,
D.Date,
isNull(E.Points,0)
from DimDate D
left join Employee E on D.Date = E.Date
where E.EmployeeId=1
AND D.Date Between '01-01-2009'and '06-01-2009'
编辑:
Select
E.EmployeeId,
D.Date,
isNull(E.Points,0)
from DimDate D
left join Employee E on D.Date = E.Date And E.EmployeeId=1
where D.Date Between '01-01-2009'and '06-01-2009'
或者
Select
E.EmployeeId,
D.Date,
isNull(E.Points,0)
from DimDate D
left join Employee E on D.Date = E.Date
where (E.EmployeeId = 1 OR E.EmployeeId is NULL)
AND D.Date Between '01-01-2009'and '06-01-2009'
关于sql - 编写 SQL 查询来替换值并包含所有日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2867669/