Removing duplicate rows by adding column value

2019-06-14 18:33发布

问题:

ID   colA  ColB   ColuC
1     a      b      4
1     a      b     -4
1     a      b      5
4     c      b      2

Wants to return as below table

ID   colA  ColB   ColuC
1    a      b      5
4    c      b      2

回答1:

You can try to use SUM with group by

SELECT ID,colA,ColB,SUM(ColuC) ColuC
FROM T
GROUP BY ID,colA,ColB


回答2:

Just use SUM():

SELECT ID, colA, colB, sum(coluC)
FROM tbl
GROUP BY ID, colA, colB;


回答3:

use aggregate function

select ID, min(colA),min(colB),max(coluC)
from t group by ID


回答4:

You can use grouping by abs() function :

select *
  from tab
 where ColuC in
     (
        select abs(coluC)
          from tab 
        group by abs(coluC)
        having count(*)=1
      );

or without subquery use

with tab( ID, ColA, ColB, ColuC ) as
(
 select 1,'a','b',4 union all
 select 1,'a','b',-4 union all
 select 1,'a','b',5 union all
 select 4,'a','b',2   
)   
select ID, ColA, ColB, abs(coluC) as coluC
  from tab 
 group by ID, ColA, ColB, abs(coluC)
having count(*)=1;


标签: sql tsql