日期:2014-05-18 浏览次数:20524 次
--> 测试数据:[test] if object_id('[test]') is not null drop table [test] create table [test]( [zuhao] int, [danweibianhao] varchar(1), [danweimingcheng] varchar(5) ) go insert [test] select 1,'A','A公司' union all select 1,'B','B公司' union all select 2,'C','C公司' union all select 2,'D','D公司' union all select 2,'E','E公司' union all select 3,'F','F公司' union all select 3,'G','G公司' go SELECT distinct a.[zuhao], [danweibianhao]=STUFF((SELECT ','+[danweibianhao] FROM [test] b WHERE a.zuhao=b.zuhao FOR XML PATH('')),1,1,''), [danweimingcheng]=STUFF((SELECT ','+[danweimingcheng] FROM [test] b WHERE a.zuhao=b.zuhao FOR XML PATH('')),1,1,'') FROM [test] a GROUP BY a.zuhao,[danweibianhao] /* zuhao danweibianhao danweimingcheng ----------------------------------------------- 1 A,B A公司,B公司 2 C,D,E C公司,D公司,E公司 3 F,G F公司,G公司 */
------解决方案--------------------
--> 测试数据:[tb] IF OBJECT_ID('[tb]') IS NOT NULL DROP TABLE [tb] GO CREATE TABLE [tb]([zuhao] INT,[danweibianhao] VARCHAR(1),[danweimingcheng] VARCHAR(5)) INSERT [tb] SELECT 1,'A','A公司' UNION ALL SELECT 1,'B','B公司' UNION ALL SELECT 2,'C','C公司' UNION ALL SELECT 2,'D','D公司' UNION ALL SELECT 2,'E','E公司' UNION ALL SELECT 3,'F','F公司' UNION ALL SELECT 3,'G','G公司' --------------开始查询-------------------------- SELECT [zuhao], danweibianhao=STUFF((SELECT ','+danweibianhao FROM [tb] WHERE [zuhao]=t.[zuhao] FOR XML PATH('')),1,1,''), danweimingcheng=STUFF((SELECT ','+danweimingcheng FROM [tb] WHERE [zuhao]=t.[zuhao] FOR XML PATH('')),1,1,'') FROM [tb] AS t GROUP BY [zuhao] ----------------结果---------------------------- /* zuhao danweibianhao danweimingcheng ----------- --------------------------------------- 1 A,B A公司,B公司 2 C,D,E C公司,D公司,E公司 3 F,G F公司,G公司 (3 行受影响) */