2

嗯,我有这个 -

Table DimDate- Date 
Table Employee-  Id,Name,Points,Date

现在 Employee 表每天都有积分,除非他们没有来......所以 Date 没有所有 Dates 条目......我的意思是例如在一周内他没有来 2 天 Employee 表只有 5 行...所以我有这个 dimdate 表,其中包含我想要加入的所有日期到 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

上面的查询给出了多个日期,我在 Date 上尝试了 group by 但不起作用。

4

2 回答 2

3

您可能不想在一个日期范围内加入这两个表,而是在一个日期上。然后按日期范围过滤记录集。例子

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'
于 2010-05-19T17:06:21.270 回答
2

我认为您需要在 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

其中 EmployeeDefinitionTable 是一个表,它唯一地列出了所有员工(或至少他们的 id 用于此问题陈述)。

这也捕获了没有积分条目的员工。

如果满足您的要求,可以将 between 语句和/或 EmployeeId 过滤移到交叉连接中。这将使交叉连接更有效。

于 2010-05-19T17:04:51.243 回答