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

Posted

技术标签:

【中文标题】带有 Group By 子句的 SQL 逗号分隔行【英文标题】:SQL comma-separated row with Group By clause 【发布时间】:2011-11-18 21:49:11 【问题描述】:

我有以下疑问:

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 一起使用的解决方案。

【问题讨论】:

【参考方案1】:

你想使用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 same unit between two tables needs order numbers in 1 cell SQL Query to get aggregated result in comma seperators along with group by column in SQL Server

【讨论】:

【参考方案2】:

没有用于连接的内置聚合函数,但本文讨论了几种替代解决方案,包括用户定义的连接聚合函数:

https://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/

【讨论】:

一开始我以为projectdms只是刮掉了没有署名的原始文章,但实际上该站点属于文章作者 链接已失效。这是另一种选择:simple-talk.com/sql/t-sql-programming/…【参考方案3】:

这将显示表、索引名称、索引类型、索引列和包含的列:

with [indexes] (table_name, index_name, column_name, index_id, key_ordinal, object_id, type_desc)
as(
SELECT  distinct
  T.[name] AS [table_name], I.[name] AS [index_name], 
  AC.[name] AS [column_name],
  I.[index_id], IC.[key_ordinal], T.[object_id], i.type_desc
FROM sys.[tables] AS T  
  INNER JOIN sys.[indexes] I ON T.[object_id] = I.[object_id]  
  INNER JOIN sys.[index_columns] IC ON I.[object_id] = IC.[object_id]  and IC.index_id=I.index_id
  LEFT OUTER JOIN sys.[all_columns] AC ON T.[object_id] = AC.[object_id] AND IC.[column_id] = AC.[column_id] 
WHERE T.[is_ms_shipped] = 0 AND I.[type_desc] <> 'HEAP'
)
select
    distinct
    db_name() as dbname,
    type_desc,
    table_name,
    index_name,
    column_name,
    STUFF((
        select ', ' + column_name
        from [indexes] t2
        where t1.table_name=t2.table_name and t1.[index_name]=t2.[index_name] and t2.[key_ordinal] = 0
        for xml path('')), 1, 2, '') inc_cols
from [indexes] t1
where t1.[key_ordinal] = 1
GROUP BY table_name, index_name, type_desc, column_name

【讨论】:

以上是关于带有 Group By 子句的 SQL 逗号分隔行的主要内容,如果未能解决你的问题,请参考以下文章

带有 WHERE 子句的 GROUP BY 以及 sql 中的 OR 的 LEFT JOIN

SQL Server:带有 GROUP BY 子句的 OUTER JOIN 不会返回所有可能的组合?

如何从表中选择带有 oracle sql 中的 group by 子句的嵌套 json 对象?

MySQL之分组查询(GROUP BY)

带有“默认值”的 SQL GROUP BY

SQL语句 group by子句后的分组项如果有多个是怎样进行分组的