代码之家  ›  专栏  ›  技术社区  ›  Aiden

删除两列匹配的位置

  •  0
  • Aiden  · 技术社区  · 7 年前

    我有两张桌子

    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
    

    现在我想编写一个删除查询,它将从地址中删除每个人的行,其中AddressMOVETODATE在OLDESTADDRESSMOVEDATE列之前

    例如

    如果运行该查询,地址表中的剩余行应该是

    PersonID             AddressMOVETODATE
    1                       20161117
    2                       20171211
    

    DELETE FROM ADDRESS WHERE PERSONID = PERSON.ID and AddressMOVETODATE < Person.OLDESTADDRESSMOVEDATE

    但它不起作用。此外,我们将如何确保只输入Person表的相应列,例如,我们不想将

    Person ID = 1 and Person.OLDESTADDRESSMOVEDATE = 20171211 (of Person 2)

    请帮忙。

    谢谢

    艾登

    1 回复  |  直到 7 年前
        1
  •  1
  •   Kannan Kandasamy    7 年前

    ;WITH cte AS
    (
        SELECT *, RowN = ROW_NUMBER() OVER (PARTITION BY ID ORDER BY AddressMoveDate DESC) FROM Address
    )
    DELETE FROM cte WHERE RowN > 1