如何在SQL中删除相反的行对?

时间:2016-01-05 17:26:50

标签: sql sql-server

我有一个事务表,并且有负sum_value和sum_units的行及其相应的行,反向(正确)sum_value和sum_units。我想删除所有这些对。

以下是如上所述的一对示例:

payer_id    order_nubber  sum_units sum_value id_3rd_level  order_date               isCorporate   payment    tk
2003931     30010577        1       54.15       101011      2013-10-25 00:00:00.000        0         Cash   12244   
2003931     1200223605     -1      -54.15       101011      2013-10-25 00:00:00.000        0         Cash   12244

我尝试了这个但是不正确。

WITH CTE AS
(
    SELECT * 
    FROM transactions
    WHERE sum_value < 0
)
DELETE tr
FROM transactions tr
INNER JOIN CTE
ON CTE.payer_id = tr.payer_id
WHERE CTE.sum_value = (-1) * tr.sum_value AND CTE.sum_units = (-1) * tr.sum_units AND 
CTE.order_date = tr.order_date AND CTE.isCorporate = tr.isCorporate AND
CTE.tk = tr.tk

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

这会查找具有相同绝对值sum_valuesum_units的所有行(可能超过两行):

--DELETE tr
SELECT *
FROM transactions AS tr
WHERE EXISTS
 ( SELECT * FROM transactions AS tr2
   WHERE tr.payer_id    = tr2.payer_id
     AND tr.sum_value   = -tr2.sum_value 
     AND tr.sum_units   = -tr2.sum_units
     AND tr.order_date  = tr2.order_date 
     AND tr.isCorporate = tr2.isCorporate 
     AND tr.tk          = t2.tk
 )

当然你应该在实际删除之前仔细检查。