假设我有这些数据:
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)
这个查询:
select * from (
select
ID, Name, Age,
row_number() over (partition by Name order by ID) [rownum]
from People
) a where [rownum] = 1
它成功地为我返回了每个唯一名称的一个人。
ID NAME AGE ROWNUM
1 Bill Jones 50 1
4 Jill Brown 44 1
3 Sam Smith 23 1
但是,为了使用 row_number()
,我必须指定 order by
,导致查询计划包含昂贵的排序操作。
我不关心返回的是哪个人;我只需要一个人的名字。
有没有办法在不排序的情况下做到这一点?
您可以在此处查看我的查询和执行计划:http://sqlfiddle.com/#!3/3ee32/1/0
最佳答案
我不知道它是否优化了一个,但它显示了你想要的记录...没有 order by 子句/.....
Select * from People a where id in (Select Top(1) id from people b where name in
(Select name from people group by name) and a.name=b.name)
关于sql - 每组选择一行而不指定顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16312943/