日期:2014-05-17  浏览次数:20452 次

两表联合查询,同时进行行列转换,请高手指点,谢谢,急急
两表联合查询,同时进行行列转换,请高手指点,谢谢,急急

表A有id,name,shj,other
表B有id,Aid,wnum,memo
他们之间的关系A.id=B.Aid

假设A表有数据
id,name,shj,other
1 b 台 99
2 b 台 100
3 张山 90

表有数据
id,Aid,wnum,memo
1 1 1 备注1
2 1 2 备注2
3 1 3 备注3
4 1 4 备注4
5 2 1 备注21
6 2 3 备注23


查询后要求实现
name shj other wnum1 wnum2 wnum3 wnum4
b 台 99 备注1 备注2 备注3 备注4
b 台 100 备注21 null 备注23 null
张山 个 90 null null null null

本人写的失去了语句
select a.name,a.shj,a.other, 
case b.wnum when 1 then b.memo else null end as wnum1,
case b.wnum when 2 then b.memo else null end as wnum2,
case b.wnum when 3 then b.memo else null end as wnum3,
case b.wnum when 4 then b.memo else null end as wnum4 
from a left outer join b on a.id=b.Aid

我写的sql语句,结果不对,本应显示在一行上,实际变成了多行,不知道哪里不对,请指教
正确的是:
name shj other wnum1 wnum2 wnum3 wnum4
b 台 99 备注1 备注2 备注3 备注4
b 台 100 备注21 null 备注23 null
而我这个错误显示为
name shj other wnum1 wnum2 wnum3 wnum4
b 台 99 备注1 null null null
b 台 99 null 备注2 null null
b 台 99 null null 备注3 null
.......

a表的数据,在b表中不一定存在,这些数据也需要列出的,请指教,谢谢 
请高手指点,多谢 

------解决方案--------------------
select a.name,a.shj,a.other, 
MAX(case b.wnum when 1 then b.memo else null END) as wnum1,
MAX(case b.wnum when 2 then b.memo else null END) as wnum2,
MAX(case b.wnum when 3 then b.memo else null END) as wnum3,
MAX(case b.wnum when 4 then b.memo else null END) as wnum4 
from a left outer join b on a.id=b.Aid
GROUP BY a.name,a.shj,a.other

/*
name shj other wnum1 wnum2 wnum3 wnum4
b 台 99 备注1 备注2 备注3 备注4
b 台 100 备注21 NULL 备注23 NULL
张山 90 NULL NULL NULL NULL NULL*/

------解决方案--------------------
declare @sql nvarchar(max)
select @sql=isnull(@sql,'')+',max(case when wnum='+rtrim(wnum)+' then memo else null end)wnum'+rtrim(wnum) from(select distinct wnum from b)t
print @sql
exec('select name,shj,other'+@sql+' from a left join b on a.id=b.aid group by name,shj,other')