带逗号分隔的SQL逗号分隔行

时间:2011-09-16 18:12:06

标签: sql sql-server sql-server-2005 aggregate-functions sql-server-group-concat

我有以下查询:

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

3 个答案:

答案 0 :(得分:23)

您想使用FOR XML PATH construct:

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 

请参阅此处的其他示例:

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

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

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