如何在 SQL 查询中使用 2 个不同的列作为条件删除行?
How to delete rows using 2 different columns as condition in a SQL query?
我的table是这样的:
Name Order Goods Date
------------------------------------------------
Michael 1 Shoes 2019/04/05
Michael 2 Groceries 2019/05/28
Michael 3 Caps 2019/03/02
Lucas 4 Shoes 2019/02/30
Lucas 5 Caps 2019/03/31
Mary 6 Shoes 2018/04/22
Mary 7 Shoes 2018/03/25
Mary 8 Groceries 2017/08/22
Mary 9 Caps 2019/01/01
如何定义查询以便删除符合以下条件的行:
首先,我想按 Name
列
对所有内容进行分组
Shoes
是我的参考。我需要检查是否有任何客户购买了“鞋子”,并且当且仅当购买日期早于该客户的“鞋子”购买日期(按名称列分组)时(即如果有任何商品除了 Shoes has been burched after the Shoes buying date, this any other good row will be deleted)
我只保留鞋子的第一次购买日期来比较。较新的日期也被删除。只保留第一个(旧的)。
所以,我将有一个 table 如下所示:
Michael 1 Shoes 2019/04/05
Michael 3 Caps 2019/03/02
Lucas 4 Shoes 2019/02/30
Mary 7 Shoes 2018/03/25
Mary 8 Groceries 2017/08/22
谢谢
您可以加入计算每个客户订购鞋子的第一个日期的聚合查询,并使用该信息过滤要删除的行:
delete t
from mytable t
inner join (
select name, min(date) min_date
from mytable
where goods = 'Shoes'
group by name
) t1 on t.name = t1.name and t.date > t1.min_date
Name | OrderID | Goods | Date
:------ | ------: | :-------- | :---------
Michael | 1 | Shoes | 2019-04-05
Michael | 3 | Caps | 2019-03-02
Lucas | 4 | Shoes | 2019-02-28
Mary | 7 | Shoes | 2018-03-25
Mary | 8 | Groceries | 2017-08-22
我的table是这样的:
Name Order Goods Date
------------------------------------------------
Michael 1 Shoes 2019/04/05
Michael 2 Groceries 2019/05/28
Michael 3 Caps 2019/03/02
Lucas 4 Shoes 2019/02/30
Lucas 5 Caps 2019/03/31
Mary 6 Shoes 2018/04/22
Mary 7 Shoes 2018/03/25
Mary 8 Groceries 2017/08/22
Mary 9 Caps 2019/01/01
如何定义查询以便删除符合以下条件的行:
首先,我想按
对所有内容进行分组Name
列Shoes
是我的参考。我需要检查是否有任何客户购买了“鞋子”,并且当且仅当购买日期早于该客户的“鞋子”购买日期(按名称列分组)时(即如果有任何商品除了 Shoes has been burched after the Shoes buying date, this any other good row will be deleted)我只保留鞋子的第一次购买日期来比较。较新的日期也被删除。只保留第一个(旧的)。
所以,我将有一个 table 如下所示:
Michael 1 Shoes 2019/04/05
Michael 3 Caps 2019/03/02
Lucas 4 Shoes 2019/02/30
Mary 7 Shoes 2018/03/25
Mary 8 Groceries 2017/08/22
谢谢
您可以加入计算每个客户订购鞋子的第一个日期的聚合查询,并使用该信息过滤要删除的行:
delete t
from mytable t
inner join (
select name, min(date) min_date
from mytable
where goods = 'Shoes'
group by name
) t1 on t.name = t1.name and t.date > t1.min_date
Name | OrderID | Goods | Date :------ | ------: | :-------- | :--------- Michael | 1 | Shoes | 2019-04-05 Michael | 3 | Caps | 2019-03-02 Lucas | 4 | Shoes | 2019-02-28 Mary | 7 | Shoes | 2018-03-25 Mary | 8 | Groceries | 2017-08-22