表结构:
objectid notetext subject
001 hello h1
001 good h2
002 yes h3
002 bye h4
我想要的显示结果:
objectid content
001 helle,h1;good,h2
002 yes,h3;bye,h4
我的sql是这样写的,可是不对呢?
select objectid,([notetext+subject]) = stuff((select ','+([notetext+subject])
from annotation as b where b.objectid = a.objectid for xml path('')),1,1,'') from annotation as a
group by objectid
------解决方案--------------------
----------------------------------------------------------------
-- 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 行受影响)
*/