Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL : select distinct of one column while ignoring other columns

So I have a table like this :

---------
id, keyid
---------
1,  3
1,  5
1,  6
2,  1
2,  1
2,  3
4,  1

I want the output of the query to be
1,3
2,1
4,1

If i use select distinct(id,keyid) from table it applies the distinct on the pair of id,keyid and not just id alone.

like image 763
newbie Avatar asked Nov 07 '11 23:11

newbie


2 Answers

select id, min(keyid) from tbl group by id
like image 193
user194076 Avatar answered Sep 21 '22 22:09

user194076


If you want the min value of KeyId for each Id, then user194076's answer will definitely work.

If you want the first occurring value of KeyId for each Id, you could use:


WITH CTE AS (
   SELECT Id, KeyId, ROW_NUMBER() OVER (PARTITION BY Id ORDER BY Id) AS RN
   FROM tbl
)

SELECT Id, KeyId FROM CTE WHERE RN = 1

I've tested both using STATISTICS IO and STATISTICS TIME and they appear to be the same in terms of performance, so really depends on what your exact needs are.

like image 39
Jeremy Wiggins Avatar answered Sep 20 '22 22:09

Jeremy Wiggins