SQL - 仅获取一列中具有最大值的行,以匹配另一列中的值

时间:2017-12-28 16:00:53

标签: sql-server

我有几个专栏。

ID - unique id for each row
Key - Correlating to a specific action (there is occasional duplicates)
Date - Lists the date and time for when each ID was created

当我有重复的密钥时,我需要找到一种只有具有更大ID的行的方法。

我有什么:

Select t1.*
From log as t1
Where t1.ID = (Select Max(t2.ID) From log as t2 Where t2.Key = t1.Key)
Order By ID

这可以消除很多行,包括一些非重复(但不是所有非重复)

有些事情消失的例子:

key 107914 -> logs [4360, 4361] Stays with 4361
key 107928 -> logs [4347, 4349, 4351, 4354, 4357] Gone
key 119207 -> logs [1189, 724] Gone
key 105079 -> logs [3399] Gone
key 107309 -> logs [4364] Stays with 4364
key 119210 -> logs [898] Gone

2 个答案:

答案 0 :(得分:0)

您可以通过此查询轻松完成

SELECT MAX(t1.Id), [key], <other columns> FROM log as t1 GROUP BY [key]

请告诉我这是否符合您的标准。

答案 1 :(得分:0)

这将有效,但仅适用于Sql Server。如果您使用的是MySql,答案会更复杂。

select r.* 
from (
    select distinct key from log
) k
cross apply (select top 1 * from log l where l.key = k.key order by id desc) r