简体   繁体   中英

Remove duplicates in Select query based on one column

I want to select without duplicate id s and keep row '5d' and not '5e' in select statement.

table

id | name
1  | a
2  | b
3  | c
5  | d
5  | e

I tried:

SELECT id, name 
FROM table t
INNER JOIN (SELECT DISTINCT id FROM table) t2 ON t.id = t2.id

For the given example an aggregation using min() would work.

SELECT id,
       min(name) name
       FROM table
       GROUP BY id;

If you want to keep the row with the smallest name then you can use not exists :

select t.* from tablename t
where not exists (
  select 1 from tablename
  where id = t.id and name < t.name
)

You can also use ROW_NUMBER() :

SELECT id, name
FROM (
    SELECT id, name, ROW_NUMBER() OVER(PARTITION BY id ORDER BY name) rn 
    FROM mytable
) x
WHERE rn = 1

This will retain the record that has the smallest name (so '5d' will come before '5e' ). With this technique, you can also use a sort criteria on another column that the one where duplicates exists (which an aggregate query with MIN() cannot do). Also, queries using window functions usually perform better than the equivalent aggregate query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM