Sql选择group by和string concat

时间:2012-04-10 06:01:59

标签: sql sql-server sql-server-2008 tsql

我有一张这样的表

ID  NAME    Amount
1   cal     100
2   cal     200
3   cal     300
4   cal     400
1   ser     500
2   ser     600
5   ser     700

我想写一个选择查询,以便我得到像这样的结果

ID  NAME            Amount
1   cal and ser     600
2   cal and ser     800
3   cal             300
4   cal             400
5   ser             700

这里我需要按ID和数量之和进行分组,并使用相同的id和不同的名称连接字符串名称

2 个答案:

答案 0 :(得分:8)

这适用于sql-server 2008

SELECT p1.ID,
       ( SELECT NAME + ' and ' 
           FROM YourTable  p2
          WHERE p2.ID = p1.ID
          ORDER BY NAME
            FOR XML PATH('') ) AS Name,
        sum(Amount)
      FROM YourTable p1
      GROUP BY ID ;

答案 1 :(得分:2)

SELECT p1.ID,  
   STUFF(( SELECT ' and ' + NAME  
       FROM YourTable  p2  
      WHERE p2.ID = p1.ID  
      ORDER BY NAME  
        FOR XML PATH('') )  
    , 1, 5, '' ) AS Name,  
    sum(Amount)  
  FROM YourTable p1  
  GROUP BY ID  

来自Vikram回答
我为结果添加了stuff