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.
source share