select a.seqno,a.compid,a.name, max(case b.fieldtype when 1 then field else '''+@blank+''' end) 座机, max(case b.fieldtype when 2 then field else '''+@blank+''' end) 手机 from table1 a group by a.name,a.seqno,a.compid
[最优解释]
哦,看错了
with tb(姓名,field,fieldtype) as( select '李','01058210000',1 union all select '王','13512555685',2 union all select '李','01052810001',1) 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.姓名
[其他解释]
CREATE table #TEMP ( NAME VARCHAR(10), TEL VARCHAR(20), type char(1) ) insert into #TEMP SELECT '李', '01058210000', '1' UNION SELECT '王', '13512555685', '2' UNION SELECT '李', '01052810001', '1'
--select*fromtb pivot(max(分数)for课程in(语文,数学,物理))a select NAME , a.[1] as 座机,a.[2] as 手机 from ( select * from #TEMP pivot (Max(tel) for [type] in([1],[2])) pvt)a [其他解释] --use StudentNew ----使用for xml path ----下边的sql语句可以将属于同组的多行的数据变成一个数据 ----结果演示 ----CityName用户名 ----北京b,d ----上海a,c,e ----create @T1 table(UserID int , UserName nvarchar(50),CityName nvarchar(50));
----insert into @T1 (UserID,UserName,CityName) values (1,'a','上海') ----insert into @T1 (UserID,UserName,CityName) values (2,'b','北京') ----insert into @T1 (UserID,UserName,CityName) values (3,'c','上海') ----insert into @T1 (UserID,UserName,CityName) values (4,'d','北京') ----insert into @T1 (UserID,UserName,CityName) values (5,'e','上海') --SELECT B.CityName,LEFT(UserList,LEN(UserList)-1) as UserList FROM --( --SELECT CityName, -- (SELECT UserName+',' FROM T1 WHERE CityName=A.CityName FOR XML PATH('')) AS UserList --FROM T1 A --GROUP BY CityName --) as B 这个应该是你需要的吧
with tb(contactorId,field,fieldtype) as( select 1,'01058210000',1 union all select 2,'13512555685',2 union all select 1,'01052810001',1), nametable(name, contactorId) as(select '李',1 union all select '王',2) select (select name from nametable where contactorId=tb1.contactorId)姓名,stuff((select ','+field from tb tb2 where fieldtype=1 and tb2.contactorId=tb1.contactorId for xml path('')),1,1,'') 座机, stuff((select ','+field from tb tb2 where fieldtype=2 and tb2.contactorId=tb1.contactorId for xml path('')),1,1,'') 手机 from tb tb1 group by tb1.contactorId