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.
select id, min(keyid) from tbl group by id
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With