Suppose I have this data:
create table People (ID int identity, Name nvarchar(50), Age int);
insert into People values
('Bill Jones', 50),
('Bill Jones', 12),
('Sam Smith', 23),
('Jill Brown', 44),
('Jill Brown', 67),
('Jill Brown', 3)
And this query:
select * from (
select
ID, Name, Age,
row_number() over (partition by Name order by ID) [rownum]
from People
) a where [rownum] = 1
It successfully returns me one person per unique name.
ID NAME AGE ROWNUM
1 Bill Jones 50 1
4 Jill Brown 44 1
3 Sam Smith 23 1
However, in order to use row_number()
, I must specify an order by
, causing the query plan to include an expensive sort operation.
I don't care about which person is returned; I just need one person per name.
Is there a way to do this without the sorting?
You can see my query and execution plan here: http://sqlfiddle.com/#!3/3ee32/1/0