关于sql:如何使用join和where子句从表中删除?

How can I delete from a table using the join and where clause?

本问题已经有最佳答案,请猛点这里访问。

下面是迄今为止我的代码,选择查询是我要从事件表中删除的查询。

1
2
3
4
5
6
7
8
9
10
DECLARE @maxsnapevent TABLE (sita VARCHAR(10), snap DATE)
INSERT INTO @maxsnapevent
SELECT sita, MAX(snapshot_date) FROM ukrmc.dbo.strategy GROUP BY sita  
--select * from @maxsnapevent


--need to delete everything that the following code gives  
SELECT events.sita, events.date, events.event FROM ukrmc.dbo.events events
JOIN @maxsnapevent MAX ON MAX.sita = events.sita  
WHERE DATE >= MAX.snap AND events.sita != 'lcypd' AND events.sita != 'lonza'

策略表中的示例数据:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
DATE          sita    Event              Snapshot_date
2018-01-01   London   Bank Holiday       2017-12-31
2018-01-02   London                      2017-12-31
2018-01-03   London                      2017-12-31
2018-01-04   London   Concert            2017-12-31
2018-01-02   London                      2018-01-01
2018-01-03   London                      2018-01-01
2018-01-04   London   Concert            2018-01-01
2018-01-01   Bham   Bank Holiday         2017-12-31
2018-01-02   Bham                        2017-12-31
2018-01-03   Bham                        2017-12-31
2018-01-04   Bham                        2017-12-31
2018-01-02   Bham                        2018-01-01
2018-01-03   Bham     Charity            2018-01-01
2018-01-04   Bham                        2018-01-01

事件表中的示例数据:

1
2
3
4
5
6
7
8
9
DATE         sita    Event
2018-01-01   London  Bank Holiday
2018-01-02   London  
2018-01-03   London  
2018-01-04   London  Concert
2018-01-01   Bham    Bank Holiday
2018-01-02   Bham  
2018-01-03   Bham  
2018-01-04   Bham    Concert

如您所见,每个快照都有几个具有多个日期的sita。


你试过下一个代码了吗?

1
2
3
4
DELETE events
FROM ukrmc.dbo.events events
JOIN @maxsnapevent MAX ON MAX.sita = events.sita  
WHERE DATE >= MAX.snap AND events.sita != 'lcypd' AND events.sita != 'lonza'