Sql 通过在一个字段上应用“分组依据”和“按其他字段排序”来选择数据
在从表中获取记录集时,我面临一个问题,例如PostCodeDistances 以下是源表:Sql 通过在一个字段上应用“分组依据”和“按其他字段排序”来选择数据,sql,sql-server,sql-server-2012,Sql,Sql Server,Sql Server 2012,在从表中获取记录集时,我面临一个问题,例如PostCodeDistances 以下是源表: SourceId | PostCode | Distance -------- | ----------| --------- 1 | 200 | 4000 1 | 300 | 2000 1 | 400 | 1000 2 | 300 | 5000 2 | 400
SourceId | PostCode | Distance
-------- | ----------| ---------
1 | 200 | 4000
1 | 300 | 2000
1 | 400 | 1000
2 | 300 | 5000
2 | 400 | 3000
2 | 500 | 4000
我想要的只是以最小距离分组ID的结果。因此,输出应该如下所示:
SourceId | PostCode | Distance
-------- | ----------| ---------
1 | 400 | 1000
2 | 400 | 3000
这个问题看起来很简单,但我的思维被卡住了,可能是我并没有以正确的方式思考解决方案。任何帮助都将不胜感激 这里有一种方法:
select top (1) with ties pcd.*
from PostCodeDistances pcd
order by row_number() over (partition by sourceId order by distance);
更传统的方法使用子查询:
select pcd.*
from (select pcd.*,
row_number() over (partition by sourceId order by distance) as seqnum
from PostCodeDistances pcd
) pcd
where seqnum = 1;
谢谢你的快速帮助。这就是我要找的。