14

我有以下查詢:SQL逗號分隔一行Group By子句

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

這當然會拋出一個異常,因爲代碼不是group by子句。每個state_fee都有一個代碼。我如何獲得此代碼以1條記錄顯示(每個state_fee每個state_fee 1個代碼)作爲逗號分隔列表?我在這裏看到了不同的解決方案,但我找不到任何與group by合作的解決方案。

回答

0

有沒有內置聚合函數來連接,但這篇文章討論了幾種可供選擇的解決方案,包括用戶自定義串連聚合函數:

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

+0

首先我想projectdms只是擦傷文章原始W/o歸屬地,但實際上該網站屬於文章作者 –

+0

該鏈接已經死亡。這是一個替代方案:https://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/ – gpinkas

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