日期:2014-05-19  浏览次数:20414 次

复杂SQL语句,请高手帮忙!谢谢!
现有三张表   #sl_1,   #sl_2,#sl_3,数据如下:
#sl_1数据:
cwhcode       cwh_name       sl_1
10                 联盟                 1
06                 龙家                 2
03                 新法                 1
#sl_2数据:
cwhcode       cwh_name       sl_2
01                 田坝                 1
05                 土木                 1
#sl_3数据:
cwhcode       cwh_name       sl_3
01                 田坝               1
现在希望得到如下查询结果:
cwhcode       cwh_name       sl_1       sl_2       sl_3
10                 联盟                 1             0             0
06                 龙家                 2             0             0
03                 新法                 1             0             0
01                 田坝                 0             1             1
05                 土木                 0             1             0
肯请高手帮忙,谢谢!

------解决方案--------------------
create table sl1(cwhcode varchar(10),cwh_name varchar(10),sl_1 int)
insert sl1 values( '10 ', '联盟 ',1)
insert sl1 values( '06 ', '龙家 ',2)
insert sl1 values( '03 ', '新法 ',1)


create table sl2(cwhcode varchar(10),cwh_name varchar(10),sl_2 int)
insert sl2 values( '01 ', '田坝 ',1)
insert sl2 values( '05 ', '土木 ',1)

create table sl3(cwhcode varchar(10),cwh_name varchar(10),sl_3 int)
insert sl3 values( '01 ', '田坝 ',1)

go

select a.*,[sl_1]=isnull(b.sl_1,0),[sl_2]=isnull(c.sl_2,0),[sl_3]=isnull(d.sl_3,0) from
(
select cwhcode,cwh_name from sl1
union
select cwhcode,cwh_name from sl2
union
select cwhcode,cwh_name from sl3
) a left join sl1 b on a.cwhcode=b.cwhcode
left join sl2 c on a.cwhcode=c.cwhcode
left join sl3 d on a.cwhcode=d.cwhcode

--结果
cwhcode cwh_name sl_1 sl_2 sl_3
---------- ---------- ----------- ----------- -----------
01 田坝 0 1 1
03 新法 1 0 0
05 土木 0 1 0
06 龙家 2 0 0