Min / Max / Group By
==== SQL QUESTION ====
Let's say I've got a table with 2 columns. 1 is a primary key, the other is another identifier that might be shared among multiple rows. Example:
id refkey
--------------------
1 ABC
2 DEF
3 ABC
4 GHI
5 ABC
6 DEF
As you can see rows 1,3 and 5 all share the same refkey "ABC", and rows 2 and 6 share refkey "DEF".
How would you go about getting a result set that listed all of the distinct refkey's and also only one of the associated primary keys? Doesn't matter which id, but it can only be one, so that your result set would look like:
id refkey
--------------------
1 ABC
2 DEF
4 GHI
Here's the kicker... you can't use a cursor. I can't figure this out for the life of me....
==== SQL ANSWER ====
SELECT DISTINCT MIN([ID]) AS [ID]
, [REFKEY]
FROM [TestDB].[dbo].[utbl_REF_KEY]
GROUP BY [REFKEY]
ORDER BY 1
ID REFKEY
1 ABC
2 DEF
4 GHI
(3 row(s) affected)

0 Comments:
Post a Comment
<< Home