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

两个表联合查询行列转换,及合并多行请高手指点,多谢
表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

表有数据
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

请高手指点,多谢

------解决方案--------------------
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  a,表B b  
where a.id=b.Aid

------解决方案--------------------

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 join b on a.id=b.aid group by name,shj,other')