sql行转列 有一样的列希望用逗号分割在一行显示
例如是这样的,fieldtype:1代表座机 2代表手机
name field fieldtype
李 01058210000 1
王 13512555685 2
李 01052810001 1
想出来这样的效果,'.'请忽略
姓名 ........ 座机 ....................................................... 手机
李......01058210000,01052810001
王 .....................................................................13512555685
如果李有手机还是会显示在李的手机列
我现在能出来普通行转列的效果
姓名 座机 手机
李 01058210000
王 13512555685
请问可以实现吗?以下是我的代码
select a.seqno,a.compid,a.name,
max(case b.fieldtype when 1 then field else '' end) 座机,
max(case b.fieldtype when 2 then field else '' end) 手机
from table1 a
group by a.name,a.seqno,a.compid
[最优解释]
select 姓名,stuff((select ','+field from tb tb2 where fieldtype=1 and tb2.姓名=tb1.姓名 for xml path('')),1,1,'') 座机,stuff((select ','+field from tb tb2 where fieldtype=2 and tb2.姓名=tb1.姓名 for xml path('')),1,1,'') 手机 from tb tb1 group by tb1.姓名
[其他解释]
该回复于2012-11-23 09:53:27被版主删除
[其他解释]
不对 你的b是哪一张表 你这刚写肯定错
[其他解释]
写错了。。我那一大串太乱了就给简化了一下 本来是右链接一张表的
[其他解释]
给出具体测试数据 把格式整理好点
[其他解释]
Create table Test
(
Name varchar(20),
Novarchar(20),
Type int
)
Go
Insert Into Test
Select '张三','123456789',1
union
Select '李四','867223',0
union
Select '王五','1232432232',1
Declare @List varchar(1000)
Set @List =cast('姓名' as char(20)) + cast('电话' as char(30))+ cast('手机' as char(30)) +char(10)+char(13)
Select
@List = @List +
cast(Name as char(20))+
cast(case when Type=0 then No else '' end as char(30))+
cast(case when Type=1 then No else '' end as char(30))+
char(10)+char(13)
From
Test
Print @List
Drop table Test
(3 row(s) affected)
姓名 电话 手机
李四 867223
王五 1232432232
张三 123456789
[其他解释]
你都没有table b,何来的正确呢