日期:2014-05-18 浏览次数:20612 次
if not object_id('tb') is null drop table tb Go Create table tb([id] int,[count] int,[name] nvarchar(1)) Insert tb select 11,22,N'a' union all select 11,22,N'b' union all select 12,33,N'c' union all select 12,33,N'd' Go select [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]
------解决方案--------------------
if object_id('[tb]') is not null drop table [tb] go create table [tb]([id] int,[count] int,[name] varchar(1)) insert [tb] select 11,22,'a' union all select 11,22,'b' union all select 12,33,'c' union all select 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 t group by id,[count] /** id count name ----------- ----------- ---------------- 11 22 a,b 12 33 c,d (2 行受影响) **/
------解决方案--------------------
/*------------------------------ -- 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) ------------------------------*/ --> 生成测试数据表:tb IF OBJECT_ID('[tb]') IS NOT NULL DROP TABLE [tb] GO CREATE TABLE [tb]([id] INT,[count] INT,[name] NVARCHAR(10)) INSERT [tb] SELECT 11,22,'a' UNION ALL SELECT 11,22,'b' UNION ALL SELECT 12,33,'c' UNION ALL SELECT 12,33,'d' GO --SELECT * FROM [tb] -->SQL查询如下: create function fn_getstr(@id int,@count int) returns varchar(20) as begin declare @s varchar(20) select @s=isnull(@s+',','')+name from tb where id=@id and @count=[count] return @s end go select distinct id,[count],name=dbo.fn_getstr(id,[count]) from tb /* id count name ----------- ----------- -------------------- 11 22 a,b 12 33 c,d (2 行受影响) */