SQL comma-separated row with Group By clause

前端 未结 3 1778
花落未央
花落未央 2020-11-27 23:13

I have the following query:

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

Thi

3条回答
  •  萌比男神i
    2020-11-27 23:50

    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:

    • SQL same unit between two tables needs order numbers in 1 cell
    • SQL Query to get aggregated result in comma seperators along with group by column in SQL Server

提交回复
热议问题