如何按分组与日期顺序将SQL行结果拼接为逗号分隔字符串?
分组拼接RESULT字段的SQL查询方案
以下是针对不同主流数据库的实现语句,你可以根据自己使用的数据库选择对应的代码:
SQL Server(2017及以上版本)
使用STRING_AGG函数直接实现分组排序拼接:
SELECT ProductNumber, Purchaseordernumber, STRING_AGG(RESULT, ',') WITHIN GROUP (ORDER BY Inspectiondate) AS [Result Seq] FROM 你的表名 GROUP BY ProductNumber, Purchaseordernumber;
注意替换语句中的你的表名为实际表名称。
MySQL
使用GROUP_CONCAT函数,通过ORDER BY指定排序规则:
SELECT ProductNumber, Purchaseordernumber, GROUP_CONCAT(RESULT ORDER BY Inspectiondate SEPARATOR ',') AS `Result Seq` FROM 你的表名 GROUP BY ProductNumber, Purchaseordernumber;
Oracle
使用LISTAGG函数实现:
SELECT ProductNumber, Purchaseordernumber, LISTAGG(RESULT, ',') WITHIN GROUP (ORDER BY Inspectiondate) AS "Result Seq" FROM 你的表名 GROUP BY ProductNumber, Purchaseordernumber;
PostgreSQL
使用STRING_AGG函数:
SELECT ProductNumber, Purchaseordernumber, STRING_AGG(RESULT, ',' ORDER BY Inspectiondate) AS "Result Seq" FROM 你的表名 GROUP BY ProductNumber, Purchaseordernumber;
内容的提问来源于stack exchange,提问作者Mohan.V
相关产品推荐
相关产品推荐

