带有 Group By 子句的 SQL 逗号分隔行 [英] SQL comma-separated row with Group By clause

查看:48
本文介绍了带有 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 

在此处查看其他示例:

这篇关于带有 Group By 子句的 SQL 逗号分隔行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆