首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

求sql多行合成一列?该如何解决

2012-03-09 
求sql多行合成一列??现在有表结构如下 :idcountname1122a1122b1233c1233d查询出来是这种1122a,b1233c,d用s

求sql多行合成一列??
现在有表结构如下 :
id count name
11 22 a
11 22 b
12 33 c
12 33 d


查询出来是这种
11 22 a,b
12 33 c,d

用sql语句怎写的啊  


[解决办法]

SQL code
if not object_id('tb') is null    drop table tbGoCreate table tb([id] int,[count] int,[name] nvarchar(1))Insert tbselect 11,22,N'a' union allselect 11,22,N'b' union allselect 12,33,N'c' union allselect 12,33,N'd'Goselect [id],       [count],       [name]=stuff((select ','+[name]                      from tb                      where [id]=t.[id] and [count]=t.[count]for xml path('')),1,1,'')from tb t group by [ID],[count]
[解决办法]
SQL code
if object_id('[tb]') is not null drop table [tb]gocreate table [tb]([id] int,[count] int,[name] varchar(1))insert [tb]select 11,22,'a' union allselect 11,22,'b' union allselect 12,33,'c' union allselect 12,33,'d' ---查询select id,[count],name=stuff((select ','+name from tb where id=t.id and [count]=t.[count] for xml path('')),1,1,'')from tb tgroup by id,[count]/**id          count       name----------- ----------- ----------------11          22          a,b12          33          c,d(2 行受影响)**/
[解决办法]
SQL code
/*--------------------------------  Author : htl258(Tony)--  Date   : 2010-04-16 11:06:38--  Version: Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86)     Jul  9 2008 14:43:34     Copyright (c) 1988-2008 Microsoft Corporation    Developer Edition on Windows NT 5.1 <X86> (Build 2600: Service Pack 3)------------------------------*/--> 生成测试数据表:tbIF OBJECT_ID('[tb]') IS NOT NULL    DROP TABLE [tb]GOCREATE TABLE [tb]([id] INT,[count] INT,[name] NVARCHAR(10))INSERT [tb]SELECT 11,22,'a' UNION ALLSELECT 11,22,'b' UNION ALLSELECT 12,33,'c' UNION ALLSELECT 12,33,'d'GO--SELECT * FROM [tb]-->SQL查询如下:create function fn_getstr(@id int,@count int)returns varchar(20)asbegin  declare @s varchar(20)  select @s=isnull(@s+',','')+name from tb where id=@id and @count=[count]  return @sendgoselect distinct id,[count],name=dbo.fn_getstr(id,[count]) from tb/*id          count       name----------- ----------- --------------------11          22          a,b12          33          c,d(2 行受影响)*/ 

热点排行