Group with with sumatenate values with sum

时间:2014-06-05 13:33:26

标签: sql sql-server sql-server-2008 sql-server-2008-r2 sql-server-2012

我有一张桌子

ReferenceNo |  Description | Amount
--------------------------------
    1222        abcd         30
    1223        efgh         10
    1223        ijkl         10
    1224        mnop         15
    1224        qrst          5
    1225        uvwx         33

我想要这样的输出:

 ReferenceNo |  Description | Amount
 --------------------------------
    1222        abcd         30
    1223        efgh ijkl    20                        
    1224        mnop qrst    20                     
    1225        uvwx         33

这里referenceNo重复我要添加金额,需要通过引用连接描述组

请帮我解决这个问题

2 个答案:

答案 0 :(得分:3)

我不确定是否有更简单的方法,但您可以使用FOR XML PATH输出使用子查询来实现

SELECT RefernceNo, 
     (SELECT Description + ' ' FROM [table] t2
      WHERE t2.ReferenceNo = t1.ReferenceNo FOR XML PATH('')
     ),
     SUM(Amount)
 FROM [table] as t1
 GROUP BY RefernceNo

答案 1 :(得分:1)

虽然查询有点冗长但使用基本SQL。使用以下查询。使其成为3部分,1。获得计数,2。获得连接值,3。获得非重复描述,最后将所有这些描述加在一起。在此处查看演示http://sqlfiddle.com/#!3/10d2d/21

SELECT REFERENCENO,NEWDESC,Total FROM
(
select X.REFERENCENO,X.NEWDESC,Y.Total,
ROW_NUMBER() OVER(PARTITION BY X.REFERENCENO 
 ORDER BY X.REFERENCENO DESC) as rn
from
(
select distinct t1.ReferenceNo,
t1.Description + t2.Description as NewDesc
from table1 t1
join table1 t2 
on t1.ReferenceNo = t2.ReferenceNo
and t1.Description <> t2.Description

union all

select [ReferenceNo], 
[Description]
from table1
where ReferenceNo in 
(
 select ReferenceNo from table1
group by [ReferenceNo]
having count(ReferenceNo) = 1
 )
) X 
inner join 
(
  select ReferenceNo,
sum(Amount) as Total
from table1
group by ReferenceNo
  ) Y
on X.ReferenceNo = Y.ReferenceNo
) TAB where rn = 1