日期:2014-05-16 浏览次数:20556 次
user value
-------------------
a 12
a 13
a 14
b 12
b 15
c 12
c 13
c 16
想输出成:
a "12,13,14"
b "12,15"
c "12,13,16" <- 这个不是3列数据,而是一个字符串而已,合并了c的三条数据,中间用逗号分割
IF EXISTS(SELECT NAME FROM sys.objects AS o WHERE o.name= 'test')
DROP TABLE test
GO
CREATE TABLE test(user1 VARCHAR(2) , VALUE VARCHAR(5))
GO
INSERT INTO test
SELECT 'a' , '12' UNION ALL
SELECT 'a' , '13' UNION ALL
SELECT 'a' , '14' UNION ALL
SELECT 'b' , '12' UNION ALL
SELECT 'b' , '15' UNION ALL
SELECT 'c' , '12' UNION ALL
SELECT 'c' , '13' UNION ALL
SELECT 'c' , '16'
-----执行查询---------
--
SELECT user1 , STUFF((SELECT ',' + VALUE FROM test AS a WHERE a.user1 = t.user1 FOR XML PATH('')),1,1,'') AS VALUE
FROM test AS t GROUP BY t.user1
/*执行结果
user1 VALUE
----- -----------
a 12,13,14
b 12,15
c 12,13,16
(3 行受影响)
*/
with a(a,b)as(
select 'a',12 union
select 'a',13 union
select 'a',14 union
select 'b',12 union
select 'b',15 union
select 'c',12 union
select 'c',13 union
select 'c',16
)
select a,
convert(varchar,MAX(case when num=1 then b else null end))+
isnull(','+convert(varchar,MAX(case when num=2 then b else null end)),'')+
isnull(','+convert(varchar,MAX(case when num=3 then b else null end)),'') from(
select num=ROW_NUMBER() over(partition by a order by b),* from a)a
group by a