SQL comma-separated row with Group By clause

与世无争的帅哥 提交于 2019-11-26 21:02:46
Adrian Carneiro

You want to use 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 

See other examples here:

BlueMonkMN

There is no built-in aggregate function to concatenate, but this article discusses several alternative solutions, including a user-defined concatenate aggregate function:

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

This will show you the table, index name, index type, indexed columns, and included columns:

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!