在SQL Server中,我有一个像这样的表:
Col-1 Col-2 Col-3
------------------------
A 123 25.13
A 456 67.00
A 789 81.89
我想要这样的输出:
Col-1 Col-2 Col-3
-----------------------------------
A 123,456,789 174.02
答案 0 :(得分:5)
样本数据:
DECLARE @T TABLE(Col1 VARCHAR(1),
Col2 INT,
Col3 FLOAT)
INSERT INTO @T( Col1, Col2, Col3 )
VALUES ('A',123,25.13),('A',456,67),('A',789,81.89)
查询:
;WITH Keys AS (SELECT Col1,
SUM(Col3) AS Col3
FROM @T
GROUP BY Col1)
SELECT Keys.Col1,
REPLACE(REPLACE(REPLACE( CONVERT (NVARCHAR(MAX),(SELECT T.Col2 AS A
FROM @T AS T
WHERE T.Col1 = Keys.Col1
FOR XML PATH(''))),'</A><A>',','),'<A>',''),'</A>','') AS Col2,
Keys.Col3
FROM Keys
结果:
Col1 Col2 Col3
A 123,456,789 174.02
答案 1 :(得分:1)
您可以将FOR XML
子句与STUFF()
函数一起使用:
select co1, stuff( (select distinct ','+cast(t1.col2 as varchar(255))
from table t1
where t1.col1 = t.col1
for xml path('')
), 1, 1, ''
) as col2,
sum(col3)
from table t
group by co1;