可能重复:
Simulating group_concat MySQL function in MS SQL Server 2005?
SQL Query for aggregation/concatenation
我试图在SQL服务器中使用stuff函数来填充某些信息。这是一个例子:
Money Age Gender
860 9 F
860 15 M
860 15 M
860 16 M
860 16 F
我想填写Age和Gender列,以便只显示一条记录如下:
Money Age Gender
860 9, 15, 15, 16, 16 F, M, M, M, F
请注意,我想分别保留年龄和性别中的两个15和3个M.
答案 0 :(得分:1)
使用FOR XML而不是东西更容易。请记住,可以欺骗FORM XML子句生成逗号分隔列表(CSV)。
以下示例应完全符合您的要求。
CREATE TABLE moneyagegender
(
[Money] INT,
[Age] INT,
[Gender] VARCHAR(2)
);
INSERT INTO moneyagegender
VALUES (860, 9, 'F'),
(860, 15, 'M'),
(860, 15, 'M'),
(860, 16, 'M'),
(860, 16, 'F');
SELECT mag.money,
(SELECT Substring((SELECT ', ' + CAST(m2.age AS VARCHAR(1024))
FROM moneyagegender m2
WHERE m2.money = mag.money
ORDER BY m2.age
FOR XML PATH('')), 3, 10000000) AS list) AS ages,
(SELECT Substring((SELECT ', ' + m3.gender
FROM moneyagegender m3
WHERE m3.money = mag.money
ORDER BY m3.age
FOR XML PATH('')), 3, 10000000) AS list) AS genders
FROM moneyagegender mag
GROUP BY mag.money;
这是输出。
Money Ages Genders
----------- -------------------- -----------------
860 9, 15, 15, 16, 16 F, M, M, M, F
(1 row(s) affected)
我希望这会有所帮助。
如果您需要更多详细信息,我会在去年发布一篇博文来解释这一点。 http://stevestedman.com/2011/10/converting-part-of-a-result-set-to-a-comma-separated-list/