编写一个SQL查询以替换值并包括所有日期
-
01-10-2019 - |
题
好吧,我有这个 -
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'
其他提示
我认为您需要在Dimdates表格和定义员工的表之间进行十字连接。这将为您提供所有员工/日期组合的记录列表。然后,该结果需要将外部连接到具有员工点记录的表。
就像是:
Select CJ.EmployeeId,CJ.Date,isNull(E.Points,0)
from (SELECT EmployeeID, D.Date
from DimDate D CROSS JOIN [EmployeeDefinitionTable] as edt) as CJ
left outer join Employee E on CJ.Date =E.Date AND CJ.EmployeeId = E.EmployeeId
where CJ.Date between '01-01-2009'and '06-01-2009'
and E.EmployeeId = 1
在雇用的情况下,可唯一列出所有员工(或至少在此问题声明中的ID)的表格。
这也捕获了没有积分条目的员工。
语句和/或员工之间的过滤之间可以将其移至十字架上,如果它适合您的要求。这将使十字架加入更加高效。
不隶属于 StackOverflow