TSQL加入以从表A中获取表B中每条记录的所有记录?

时间:2013-02-25 22:13:32

标签: tsql join

我有两张桌子:

 PeriodId  Period   (Periods Table)
 --------  -------
 1         Week 1
 2         Week 2
 3         Week 3


 EmpId  PeriodId  ApprovedDate  (Worked Table)
 -----  --------  ------------
 1      1         Null
 1      2         2/28/2013
 2      2         2/28/2013

我正在尝试编写一个导致此结果的查询:

 EmpId  Period    Worked     ApprovedDate
 -----  --------  ---------  ------------
 1      Week 1    Yes        Null
 1      Week 2    Yes        2/28/2013
 1      Week 3    No         Null
 2      Week 1    No         Null
 2      Week 2    Yes        2/28/2013
 2      Week 3    No         Null

我的想法是,我需要每个Emp的Periods表中的每个Period。如果Worked表中没有记录,则“No”值将被置于Worked字段。

获得此结果的TSQL是什么样的?

(注意:如果它有帮助我也可以访问每个员工都有EmpId和LastName的Employee表。出于性能原因,我希望不需要这个,但如果我这样做,那就这样吧。)

1 个答案:

答案 0 :(得分:4)

您应该可以使用以下内容:

select p.empid,
  p.period,
  case 
    when w.PeriodId is not null 
    then 'Yes' 
    else 'No' End Worked,
  w.ApprovedDate
from
(
  select p.periodid, p.period, e.empid
  from periods p
  cross join (select distinct EmpId from worked) e
) p
left join worked w
  on p.periodid = w.periodid
  and p.empid = w.empid
order by p.empid

请参阅SQL Fiddle with Demo