SQL Server将多行组合成单行

时间:2016-06-23 22:34:23

标签: sql sql-server

非常感谢任何帮助。我有以下查询,需要帮助修改它以将多行组合成单行,数据用逗号分隔。我已附上image供您参考。

select CT_ID
     , Acct_Group
     , (source + ' - '
        +  cast(count(*) as nvarchar(20)) 
        +' account groups have total amounts in file A more or less than 25% of File B AMount'
        ) as Error  
from (
     select CT_ID
          , source
          , acct_group
          , sum(balance) as Balance
          , sum(k_new_balance) as K_New_Balance 
     from tblGroups 
     group by acct_group, source, CT_ID 
     ) as x
where abs((K_New_Balance - Balance)/nullif(Balance, 0)) >=0.25 
group by source, CT_ID,Acct_group 
order by CT_ID

2 个答案:

答案 0 :(得分:0)

如果将输出放入cte或temp表中,可以使用row_number来获取所需的输出,这可能会有所帮助,如:

 select * into #T from (
     select 'l1' CT_ID , 'ab' Acc_Group union
     select 'l1' CT_ID , 'rr' Acc_Group union
     select 'pl1' CT_ID , 'ab' Acc_Group union
     select 'pl1' CT_ID , 'rr' Acc_Group union
     select 'pl1' CT_ID , 'dd' Acc_Group) x



     select x.CT_ID , x.Acc_Group + isnull(','+y.Acc_Group,'') +  isnull(','+z.Acc_Group ,'') Acc_Group,ct.ct

     from (select * ,row_number() over ( partition by CT_ID order by Acc_Group) rowid    from #T) x
     left join (select * ,row_number() over ( partition by CT_ID order by Acc_Group) rowid   from #T) y
     on x.rowid = y.rowid -1
     and x.CT_ID = y.CT_ID
     left join (select * ,row_number() over ( partition by CT_ID order by Acc_Group) rowid   from #T) z
     on x.rowid = z.rowid -2
     and x.CT_ID = z.CT_ID
     left join ( select CT_ID,count(*) ct from #T group by CT_ID) ct
     on ct.CT_ID = x.CT_ID
     where x.rowid = 1

答案 1 :(得分:0)

谷歌搜索“sql string concatenation”

首批结果之一的示例:https://sqlandme.com/2011/04/27/tsql-concatenate-rows-using-for-xml-path/

SELECT      CAT.Name AS [Category],
            STUFF((    SELECT ',' + SUB.Name AS [text()]
                — Add a comma (,) before each value
                    FROM Production.ProductSubcategory SUB
                    WHERE
                    SUB.ProductCategoryID = CAT.ProductCategoryID
                    FOR XML PATH('') — Select it as XML
                    ), 1, 1, '' )
                    — This is done to remove the first character (,)
                    — from the result
        AS [Sub Categories]
FROM  Production.ProductCategory CAT

基本上,允许您将子查询的结果作为分隔列表(在本例中为逗号)加入。然后,您可以在子查询中包含该选项以选择所有代码。