som*_*ter 7 mysql sql sql-server
我想查询上面的图片.
左图是原始数据,右图是查询数据.
select distinct ID, Nickname, Revision
from test_table
Run Code Online (Sandbox Code Playgroud)
此查询不显示上面的图片.
如何避免重复数据?
Gur*_*ngh 15
如果是SQL Server,则ROW_NUMBER在子查询中使用窗口函数:
select t.id, t.nickname, t.revision
from (
select t.*, row_number() over (
partition by t.id order by t.revision desc
) rn
from your_table t
) t
where rn = 1;
Run Code Online (Sandbox Code Playgroud)
或者使用TOP with ties具有ROW_NUMBER:
select top 1 with ties *
from your_table
order by row_number() over (
partition by id order by revision desc
)
Run Code Online (Sandbox Code Playgroud)
如果MySQL:
select t.*
from your_table t
inner join (
select id, MAX(revision) revision
from your_table
group by id
) t1 on t.id = t1.id
and t.revision = t1.revision;
Run Code Online (Sandbox Code Playgroud)
使用的另一招 TOP 1 with TIES
SELECT Top 1 with ties *
FROM your_table t
Order by row_number() over (partition BY t.id order by t.revision DESC)
Run Code Online (Sandbox Code Playgroud)