SQL: select different from one column, 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 different (id, keyid) from the table, it applies the distinguishing characters to the pair id, keyid, and not just one.

+6
source share
2 answers
 select id, min(keyid) from tbl group by id 
+13
source

If you want a minimum KeyId for each Id, then user194076's answer will definitely work.

If you want to get the first KeyId value for each Id, you can 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 tested both using STATISTICS IO and STATISTICS TIME , and they look the same in terms of performance, so it really depends on your specific needs.

+1
source

Source: https://habr.com/ru/post/900980/


All Articles