代码之家  ›  专栏  ›  技术社区  ›  Ashkan Mobayen Khiabani

SQL Server:删除可交换列中的重复项

  •  0
  • Ashkan Mobayen Khiabani  · 技术社区  · 6 年前

    我有这个问题:

    select 
        OSFES97.CodeId, OSFBA97.CodeId, OSFES97.ReceiveDate
    from 
        StockArchives OSFES97 
    inner join 
        StockArchives OSFBA97 on OSFBA97.ReceiveDate = OSFES97.ReceiveDate
    where 
        OSFES97.CodeId <> OSFBA97.CodeId 
    

    它返回如下结果:

    CodeId    CodeId    ReceiveDate
    ------------------------------------------
    1         2         2019-01-13 15:55:20.537
    2         1         2019-01-13 15:55:20.537
    1         2         2019-01-13 15:55:30.537
    2         1         2019-01-13 15:55:30.537
    

    以下记录为我使用的副本(如果它们相同 ReceiveDate ,我想删除其中一个,并实现以下结果:

    CodeId    CodeId    ReceiveDate
    ------------------------------------------
    1         2         2019-01-13 15:55:20.537
    1         2         2019-01-13 15:55:30.537
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Mureinik    6 年前

    使用 <> 运算符将创建这些(逻辑)重复项。相反,您可以决定要使用较低ID的列并使用 < > 因此。例如。:

    SELECT     OSFES97.CodeId, OSFBA97.CodeId, OSFES97.ReceiveDate
    FROM       StockArchives OSFES97
    INNER JOIN StockArchives OSFBA97 ON OSFBA97.ReceiveDate = OSFES97.ReceiveDate
    WHERE       OSFES97.CodeId < OSFBA97.CodeId 
    -- Here -------------------^