通过添加列值来删除重复的行

时间:2018-12-18 14:52:32

标签: sql tsql

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

希望返回下表

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

4 个答案:

答案 0 :(得分:3)

您可以尝试将SUMgroup by一起使用

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

答案 1 :(得分:1)

只需使用SUM()

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

答案 2 :(得分:0)

使用聚合函数

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

答案 3 :(得分:0)

您可以通过abs()函数使用分组:

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

或不使用子查询

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;