Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server : how to avoid duplicate data?

enter image description here

I want to query above picture.

Left picture is original data, right picture is query data.

select distinct ID, Nickname, Revision 
from test_table

This query do not show above picture.

How to avoid duplicate data?

like image 371
somputer Avatar asked Dec 28 '16 05:12

somputer


People also ask

How do you prevent duplicates in SQL Server?

The SQL DISTINCT keyword, which we have already discussed is used in conjunction with the SELECT statement to eliminate all the duplicate records and by fetching only the unique records.

How can we avoid duplicate values in SQL?

If you want the query to return only unique rows, use the keyword DISTINCT after SELECT . DISTINCT can be used to fetch unique rows from one or more columns. You need to list the columns after the DISTINCT keyword.


2 Answers

If SQL Server, using window function ROW_NUMBER in subquery:

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;

Or using TOP with ties with ROW_NUMBER:

select top 1 with ties *
from your_table
order by row_number() over (
        partition by id order by revision desc
        )

If 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;
like image 77
Gurwinder Singh Avatar answered Nov 05 '22 13:11

Gurwinder Singh


Another trick using 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) 
like image 33
Pரதீப் Avatar answered Nov 05 '22 13:11

Pரதீப்