怎样合并表中的字段
ID CID Desc
1 2 西瓜
2 3 萝卜
3 3 芹菜
4 2 苹果
5 1 豆腐
6 2 葡萄
需求:我要获得所有CID=2的水果
数据在一处显示,逗号隔开,如我喜欢的水果有:西瓜,苹果,葡萄
2012最后一天,大牛给力。
[解决办法]
cursor is ok for this issue
[解决办法]
--> 测试数据:#tb
IF OBJECT_ID('TEMPDB.DBO.#tb') IS NOT NULL DROP TABLE #tb
GO
CREATE TABLE #tb([ID] INT,[CID] INT,[Desc] VARCHAR(4))
INSERT #tb
SELECT 1,2,'西瓜' UNION ALL
SELECT 2,3,'萝卜' UNION ALL
SELECT 3,3,'芹菜' UNION ALL
SELECT 4,2,'苹果' UNION ALL
SELECT 5,1,'豆腐' UNION ALL
SELECT 6,2,'葡萄'
--------------开始查询--------------------------
SELECT [CID],STUFF((SELECT ','+[Desc] FROM #tb WHERE [CID]=a.[CID] FOR XML PATH('')),1,1,'')
FROM #tb AS a
GROUP BY [CID]
----------------结果----------------------------
/*
CID(无列名)
1豆腐
2西瓜,苹果,葡萄
3萝卜,芹菜
*/
[解决办法]
select cid,stuff((select ','+[desc] from table where a.cid=cid for xml path('')),1,1,'')
from table as a where cid=2
group by cid
select b.[cid],left(StuList,len(StuList)-1)as tb from (
SELECT [cid],
(SELECT [desc]+',' FROM tb
WHERE [cid]=a.[cid]
FOR XML PATH('')) AS StuList
FROM tb A
GROUP BY cid
) B
if OBJECT_ID('test')is not null
drop table test
go
create table test(id int,clid int,[desc] varchar(20))
insert into test
select 1, 2, '西瓜' union all
select 2, 3, '萝卜' union all
select 3, 3, '芹菜' union all
select 4, 2, '苹果' union all
select 5, 1, '豆腐' union all
select 6, 2, '葡萄'
declare @val varchar(max)
select @val=ISNULL(@val+',','')+[desc] from test where clid=2
select @val