2016-12-28 7 views
7

enter image description hereSQL Server:重複するデータを避けるには?

私は上記の画像を照会したいと思います。

左の画像は元のデータ、右の画像はクエリデータです。

select distinct ID, Nickname, Revision 
from test_table 

このクエリは上記の画像には表示されません。

データの重複を避けるにはどうすればよいですか?

+0

あなたは現在どのような結果を得ていますか? –

+0

最後のリビジョンデータのみを取得したい。私はSQL Serverを使用しています。 – somputer

+0

@JaydipJ - BobTは、ユーザーID 1の3番目のバージョンです。 – Hogan

答えて

16

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 tiesROW_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; 
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) 
1
select distinct ID, Nickname, MAX(Revision) 
from test_table 
group by ID 
+0

同じ文でdistinctとgroup by句の両方を使用する必要はありません –

関連する問題