读书人

复杂SQL语句请高手帮忙!多谢

发布时间: 2012-01-18 00:23:26 作者: rapoo

复杂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
10 联盟 1 0 0

(所影响的行数为 5 行)


[解决办法]
create table #sl_1(cwhcode varchar(10), cwh_name varchar(10), sl_1 int)
insert #sl_1 select '10 ', '联盟 ', 1
union all select '06 ', '龙家 ', 2
union all select '03 ', '新法 ', 1

create table #sl_2(cwhcode varchar(10), cwh_name varchar(10), sl_2 int)
insert #sl_2 select '01 ', '田坝 ', 1
union all select '05 ', '土木 ', 1

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

select cwhcode, cwh_name,
sl_1=sum(case when ID=1 then sl_1 else 0 end),
sl_2=sum(case when ID=2 then sl_1 else 0 end),
sl_3=sum(case when ID=3 then sl_1 else 0 end)
from (
select *, 1 as ID from #sl_1
union all
select *, 2 from #sl_2
union all
select *, 3 from #sl_3
)tmp group by cwhcode, cwh_name
[解决办法]
--result
cwhcode cwh_name sl_1 sl_2 sl_3
---------- ---------- ----------- ----------- -----------
10 联盟 1 0 0
06 龙家 2 0 0
01 田坝 0 1 1
05 土木 0 1 0
03 新法 1 0 0

(5 row(s) affected)

读书人网 >SQL Server

热点推荐