SQL-删除总和= 0的记录

时间:2020-07-16 19:14:22

标签: sql sql-server sql-delete

我有一个具有以下值的表:
enter image description here

如果具有相同ID的值之和= 0,我想将其从表中删除。因此结果应如下所示:
enter image description here

我拥有的代码:

DELETE FROM tmp_table
WHERE ID in 
            (SELECT ID
            FROM tmp_table WITH(NOLOCK) 
            GROUP BY ID
            HAVING SUM(value) = 0)

仅删除ID = 2的行。

UPD:包括其他示例: 黄色的行需要删除
enter image description here

2 个答案:

答案 0 :(得分:2)

您的查询正常工作,因为总数为零的唯一组是id 2,其他子组的总数为零(例如前两个的id 1),但是总数为所有这些记录是-3。

您想要的是一种更复杂的算法来执行“ bin packing”以删除总计为零的子组。

答案 1 :(得分:1)

您可以使用窗口函数来完成所需的工作-通过枚举每个id的值。使用子查询进行操作:

with t as (
      select t.*,
             row_number() over (partition by id, value order by id) as seqnum
      from tmp_table t
     )
delete from t
    where exists (select 1
                  from t t2
                  where t2.id = t.id and t2.value = - t.value and t2.seqnum = t.seqnum
                 );

您还可以使用第二层窗口功能来做到这一点:

with t as (
      select t.*,
             row_number() over (partition by id, value order by id) as seqnum
      from tmp_table t
     ),
     tt as (
      select t.*, count(*) over (partition by id, abs(value), seqnum) as cnt
      from t
     )
delete from tt
    where cnt = 2;
相关问题