日期:2014-05-18  浏览次数:20496 次

[Help]有难度的左连接语句写法
A表
工号     姓名
01           小明
02           小红
......

B表
编号   工号           类型         天数         日期
1               01         请假         0.5           2007-6-1
2               01         请假         0.5           2007-6-1
3               01         休息         1               2007-6-1
4               01         出差         1               2007-7-1
5               02         请假         1               2007-6-1
......

请问如何写出以下查询结果:
工号       姓名         日期                 请假       休息       出差
01           小明         2007-6-1           1               1                 0
01           小明         2007-7-1           0               0                 1
02           小红         2007-6-1           1               0                 0
02           小红         2007-7-1           0               0                 0
......

------解决方案--------------------
select
A.工号,A.姓名,B.日期,
sum(case B.类型 when '请假 ' then B.天数 else 0 end) as 请假,
sum(case B.类型 when '休息 ' then B.天数 else 0 end) as 休息,
sum(case B.类型 when '出差 ' then B.天数 else 0 end) as 出差
from
A
left join
B
on
A.工号=B.工号
group by
A.工号,A.姓名,B.日期
------解决方案--------------------
select 工号,姓名,日期,
sum(case 类型 when 请假 then 1 else 0 end) 请假,
sum(case 类型 when 休息 then 1 else 0 end) 休息,
sum(case 类型 when 出差 then 1 else 0 end) 出差
from A left join B on A.工号 = B.工号
group by A.工号,B.日期
------解决方案--------------------
Select b.工号,a.姓名,b.日期,
请假=(Case when 类型= '请假 ' then 1 else 0 end),
休息=(Case when 类型= '休息 ' then 1 else 0 end),
出差=(Case when 类型= '出差 ' then 1 else 0 end)
from A表 as a Left Join B表 as b on a.工号=b.工号
------解决方案--------------------
select
a.工号,
a.姓名,
b.日期,
请假=sum(case b.类型 when '请假 ' then b.天数 else 0 end),
休息=sum(case b.类型 when '休息 ' then b.天数 else 0 end),
出差=sum(case b.类型 when '出差 ' then b.天数 else 0 end)