如何使用 SQL 查找最后日期可能的反向重复项?

How to find possible reverse duplicates by last date with SQL?

一直试图解决这个问题但没有成功...我有一个 table 数据:

CREATE TABLE [dbo].[test](
    [ID1] [varchar](50) NULL,
    [ID2] [varchar](50) NULL,
    [Date] [date] NULL
)

INSERT INTO test VALUES (123,124,'2018-01-01'),
                        (123,125,'2018-01-01'),
                        (125,126,'2018-01-02'),
                        (123,125,'2018-01-02'),
                        (125,123,'2018-01-03'),
                        (126,121,'2018-01-04')

因为我只需要两对之间的 LAST 关系,所以结果应该如下所示:

ID1 ID2 Date
123 124 2018-01-01
125 126 2018-01-02
125 123 2018-01-03
126 121 2018-01-04

我发现许多解决方案只包含两列,但 none 包含最后一个日期。

谢谢!

阿莱斯

您只是在寻找聚合吗?

select id1, id2, max(date)
from t
group by id1, id2;

编辑:

您似乎想不考虑方向地对待 id1/id2 对。如果是这样,请使用 row_number():

select id1, id2, date
from (select t.* ,
             row_number() over (partition by (case when id1 < id2 then id1 else id2 end),
                                             (case when id1 < id2 then id2 else id1 end)
                                order by date desc
                               ) as seqnum                                             
      from test t
     ) t
where seqnum = 1;

Here 是此解决方案的 SQL Fiddle。