2017-06-01 38 views
1

我在從我的表中讀取記錄集時遇到一個問題,那就是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 

問題看似簡單,但我的腦海裏停留,可能是我沒有在正確的方式思考解決方案。任何幫助將不勝感激。

回答

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; 
+0

感謝快速幫助。這正是我所期待的。 –

相關問題