简体   繁体   English

SQL查询删除表中的相关记录

[英]SQL Query to remove related records in table

I have a simple table with basic sales info like NAME, PRICE, STATUS. 我有一个简单的表格,其中包含基本的销售信息,例如名称,价格,状态。 for each customer interaction they are input into the table with NAME and PRICE. 对于每次客户互动,他们都使用NAME和PRICE输入到表格中。 if that customer has cancelled the deal then another record is added with the NAME, negative PRICE, and STATUS = cancelled. 如果该客户取消了交易,则将添加另一条记录,其中包含名称,负PRICE和STATUS =已取消。 Here is an example table 这是一个示例表

+------+--------+-----------+
| NAME | PRICE  |  STATUS   |
+------+--------+-----------+
| bob  |    100 |           |
| mary |    100 |           |
| mary |   -100 | cancelled |
| andy |    250 |           |
| mary |    250 |           |
+------+--------+-----------+

What I want to do is remove both the positive and negative records for deals that have cancelled so that the resulting table would look like this. 我想做的是删除已取消交易的正向和负向记录,以使结果表看起来像这样。

+------+--------+-----------+
| NAME | PRICE  |  STATUS   |
+------+--------+-----------+
| bob  |    100 |           |
| andy |    250 |           |
| mary |    250 |           |
+------+--------+-----------+

Any suggestions on how to do this in SQL? 关于如何在SQL中执行此操作的任何建议?

Join the table with itself to match the related records: 将表与自身连接起来以匹配相关记录:

DELETE t1
FROM yourTable AS t1
JOIN yourTable AS t2 ON t1.name = t2.name AND t1.price IN (t2.price, -t2.price)
WHERE t2.status = 'canceled'

The join finds rows that have the same name, and the price is either the same price or the negative of the price. 联接查找具有相同名称的行,并且价格要么是相同的价格,要么是价格的负数。 The WHERE clause restricts this to matching rows that are canceled. WHERE子句将其限制为被取消的匹配行。

DEMO 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM