我有两张桌子
Person (contain oldest date (farthest in future) when person moved OR WILL moved to another address)
ID OLDESTADDRESSMOVEDATE
1 20161117
2 20171211
3 20160101
Address
PersonID AddressMOVETODATE
1 20161117
1 20161111
1 20141018
2 20171211
2 20151210
现在我想编写一个DELETE查询,它将为PERSON中的每个人删除地址,其中AddressMOVETODATE比OLDESTADDRESSMOVEDATE colum中的那个更早
e.g。
如果我运行该查询,则ADDRESS表中的其余行应为
PersonID AddressMOVETODATE
1 20161117
2 20171211
我试过了
DELETE FROM ADDRESS WHERE PERSONID = PERSON.ID and AddressMOVETODATE < Person.OLDESTADDRESSMOVEDATE
但它不起作用。另外,我们如何确保只输入Person表的CORRESPONDING列,例如我们不想通过放置
来搞砸 Person ID = 1 and Person.OLDESTADDRESSMOVEDATE = 20171211 (of Person 2)
请帮忙。
谢谢,
艾登
答案 0 :(得分:1)
您可以使用row_number,cte和delete
进行查询;WITH cte AS
(
SELECT *, RowN = ROW_NUMBER() OVER (PARTITION BY ID ORDER BY AddressMoveDate DESC) FROM Address
)
DELETE FROM cte WHERE RowN > 1