我有一张满是重复表的桌子。我正在尝试转换它们,以便可以在两个字段(例如identifier1identifier2)上放置唯一约束。

我想将这些重复项“折叠”成单个记录,但是我的记录包含不同的字符串。在这种情况下,我想保持最后一动(将ID保持最高的ID丢弃其余的ID)。

例如,我可以将下面的startDateMIN()汇总在一起-但是如何只获取最新的location

    id | identifier1 | identifier2 | location   | startDate
    1  | alice       | 0001        | ambridge   | 2016-01-01
    2  | bob         | 1312        | brigadoon  | 2017-01-01
    3  | alice       | 0001        | brigadoon  | 2017-05-01
    4  | bob         | 9999        | brigadoon  | 2015-01-01
    5  | celeste     | 1234        | cittegazze | 2011-01-01

    id | identifier1 | identifier2 | location   | startDate
    6  | alice       | 0001        | brigadoon  | 2016-01-01
    7  | bob         | 1312        | brigadoon  | 2017-01-01
    8  | bob         | 9999        | brigadoon  | 2015-01-01
    9  | celeste     | 1234        | cittegazze | 2011-01-01

最佳答案

尝试这个:

select A.identifier1, A.identifier2, A.startDate, B.Location from (
    select identifier1,
           identifier2,
           MIN(startDate) AS startDate
    from TABLE_NAME
    group by identifier1, identifier2
) AS A JOIN TABLE_NAME AS B
ON (A.identifier1 = B.identifier1 and A.identifier2 = B.identifier2 and A.startDate = B.startDate)

10-06 05:48