繁体   English   中英

SQL Server将多行合并为单行

[英]SQL Server combine multiple rows into single row

任何帮助深表感谢。 我有以下查询,并且在修改它以将多行合并为单行且数据用逗号分隔时需要帮助。 我已附上图片供您参考。

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

如果将输出放入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

用谷歌搜索“ SQL字符串连接”

来自第一个结果之一的示例: 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

基本上,您可以将子查询的结果作为分隔列表(在这种情况下为逗号)进行联接。 然后,您可以将其包含在子查询中以选择所有代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM