我从我的表中获取记录集时遇到一个问题,如PostCodeDistances。
这是源表:
SourceId | PostCode | Distance
-------- | ----------| ---------
1 | 200 | 4000
1 | 300 | 2000
1 | 400 | 1000
2 | 300 | 5000
2 | 400 | 3000
2 | 500 | 4000
我想要的只是将Ids分组为最小距离的结果。所以输出应该是:
SourceId | PostCode | Distance
-------- | ----------| ---------
1 | 400 | 1000
2 | 400 | 3000
问题似乎很简单,但我的思绪陷入困境,可能是我没有以正确的方式思考解决方案。任何帮助将受到高度赞赏。
答案 0 :(得分:2)
这是一种方法:
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;