SQL - 删除总和 = 0 的记录
SQL - delete record where sum = 0
我有一个 table 具有以下值:
如果具有相同 ID 的值总和 = 0,我想将它们从 table 中删除。所以结果应该是这样的:
我的代码:
DELETE FROM tmp_table
WHERE ID in
(SELECT ID
FROM tmp_table WITH(NOLOCK)
GROUP BY ID
HAVING SUM(value) = 0)
只删除 ID = 2 的行。
UPD:包括附加示例:
需要删除黄色行
您的查询工作正常,因为唯一总计为零的组是 id
2,其他组的子组总计为零(例如前两个 id
1)但是所有这些记录的总数是 -3。
你想要的是一个更复杂的算法来执行“bin packing”以删除总和为零的子组。
您可以使用 window 函数做您想做的事——通过枚举每个 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
);
您还可以使用第二层 window 函数来执行此操作:
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;
我有一个 table 具有以下值:
如果具有相同 ID 的值总和 = 0,我想将它们从 table 中删除。所以结果应该是这样的:
我的代码:
DELETE FROM tmp_table
WHERE ID in
(SELECT ID
FROM tmp_table WITH(NOLOCK)
GROUP BY ID
HAVING SUM(value) = 0)
只删除 ID = 2 的行。
UPD:包括附加示例:
需要删除黄色行
您的查询工作正常,因为唯一总计为零的组是 id
2,其他组的子组总计为零(例如前两个 id
1)但是所有这些记录的总数是 -3。
你想要的是一个更复杂的算法来执行“bin packing”以删除总和为零的子组。
您可以使用 window 函数做您想做的事——通过枚举每个 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
);
您还可以使用第二层 window 函数来执行此操作:
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;