我有一个保存人员代码的表。
当我从该表中选择时,我得到3行结果,例如:
2129,3394,3508,3534
2129,3508
4056
我要在创建选择结果时将其合并为一行,例如:
2129,3394,3508,3534,2129,3508,4056
或不同的值,例如:
2129,3394,3508,3534,4056
答案 0 :(得分:2)
理想情况下,您应该避免在表中完全存储CSV数据。话虽如此,对于您的第一个结果集,我们可以尝试使用STRING_AGG
:
SELECT STRING_AGG(col, ',') AS output
FROM yourTable;
您的第二个要求比较棘手,我们可以尝试通过表格删除重复项:
WITH cte AS (
SELECT DISTINCT VALUE AS col
FROM yourTable t
CROSS APPLY STRING_SPLIT(t.col, ',')
)
SELECT STRING_AGG(col, ',') WITHIN GROUP (ORDER BY CAST(col AS INT)) AS output
FROM cte;
答案 1 :(得分:1)
我通过使用FOR XML PATH
和SELECT
STUFF((SELECT ',' + US.remain_uncompleted
FROM Table_request US
WHERE exclusive = 0 AND reqact = 1 AND reqend = 0
FOR XML PATH('')), 1, 1, '')
解决了这个问题:
[{
"lastnameID": "1",
"name": "Doe"
}, {
"lastnameID": "2",
"name": "Smith"
}]
谢谢蒂姆