SQL Server:如何避免重复数据?

时间:2016-12-28 05:10:57

标签: mysql sql sql-server

enter image description here

我想查询上面的图片。

左图是原始数据,右图是查询数据。

select distinct ID, Nickname, Revision 
from test_table

此查询未显示上图。

如何避免重复数据?

3 个答案:

答案 0 :(得分: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;

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
        )

如果是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;

答案 1 :(得分:5)

使用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) 

答案 2 :(得分:1)

select distinct ID, Nickname, MAX(Revision) 
from test_table 
group by ID