日期:2014-05-16 浏览次数:20710 次
----------------------------------------------------------------
-- Author :fredrickhu(小F,向高手学习)
-- Date :2014-03-26 10:08:47
-- Verstion:
-- Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86)
-- Jul 9 2008 14:43:34
-- Copyright (c) 1988-2008 Microsoft Corporation
-- Enterprise Edition on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([objectid] varchar(3),[notetext] varchar(5),[subject] varchar(2))
insert [tb]
select '001','hello','h1' union all
select '001','good','h2' union all
select '002','yes','h3' union all
select '002','bye','h4'
--------------开始查询--------------------------
select objectid, [content]=stuff((select ';'+[notetext]+','+[subject] from tb where objectid=t.objectid for xml path('')), 1, 1, '')
from tb t
group by objectid
----------------结果----------------------------
/* objectid content
-------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
001 hello,h1;good,h2
002 yes,h3;bye,h4
(2 行受影响)
*/