带有 Group By 子句的 SQL 逗号分隔行

我有以下查询:

SELECT
  Account,
  Unit,
  SUM(state_fee),
  Code
FROM tblMta
WHERE MTA.Id = '123'
GROUP BY Account,Unit

这当然会引发异常,因为代码不在 group by 子句中.每个 state_fee 都有一个代码.如何让此代码以逗号分隔列表的形式显示在 1 个记录中(每个 state_fee 1 个代码,即每个单位的多个 state_fee)?我在这里查看了不同的解决方案,但找不到任何适用于 group by 的解决方案.

This of course throws an exception because the Code is not in the group by clause. Each state_fee has a code. How do I get this code to display in 1 record (1 code per state_fee which is multiple state_fee per unit) as a comma-separated list? I looked into different solutions on here but I couldn't find any that worked with a group by.

推荐答案

您想使用 FOR XML PATH 构造:

SELECT ACCOUNT, 
       unit, 
       SUM(state_fee), 
       Stuff((SELECT ', ' + code 
              FROM   tblmta t2 
              WHERE  t2.ACCOUNT = t1.ACCOUNT 
                     AND t2.unit = t1.unit 
                     AND t2.id = '123' 
              FOR XML PATH('')), 1, 2, '') [Codes] 
FROM   tblmta t1 
WHERE  t1.id = '123' 
GROUP  BY ACCOUNT, 
          unit 

在此处查看其他示例:

  • SQL两个表之间的相同单位需要 1 个单元格中的订单号
  • SQL 查询以获取逗号分隔符中的聚合结果以及 SQL Server 中的按列分组

相关文章