I want to get the row per group with the min value of two columns.
I have a table that has listings for items I want, as well as their cost and distance from me.
mytable:
item | cost | dist
-----+------+---------
1 | $2 | 1.0
1 | $3 | 0.5
1 | $4 | 2.0
2 | $2 | 2.0
2 | $2 | 1.5
2 | $2 | 4.0
2 | $8 | 1.0
2 | $12 | 3.0
3 | $1 | 5.0
For each item, I want to get the row that has the min cost, then if there are multiple of the min cost, get the one with the min dist
so my result would be
item | cost | dist
-----+------+---------
1 | $2 | 1.0
2 | $2 | 1.5
3 | $1 | 5.0
I know I can achieve this result using
SELECT *
, ROW_NUMBER() OVER(PARTITION BY item ORDER BY cost ASC, dist ASC) as [RID]
FROM mytable
WHERE [RID] = 1
but the problem comes when I have 100,000 items each with 100,000 listings, and sorting the whole table becomes incredibly time-consuming.
Since I only need the top 1 of each group, I'm wondering if there is another way to get the result I want without sorting the whole table of 10,000,000,000 entries.
Currently using SQL Server 2012