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

xwhope 2007-04-21 03:19:21
现有三张表 #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
肯请高手帮忙,谢谢!
...全文
216 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
marco08 2007-04-21
  • 打赏
  • 举报
回复
--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)

marco08 2007-04-21
  • 打赏
  • 举报
回复
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
点点星灯 2007-04-21
  • 打赏
  • 举报
回复
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 行)

34,588

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧