使用 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/