2012-10-02 27 views
0

下面的查詢給我一行,因爲b.id是固定的。我想要一個查詢,我可以給一組ID並獲得每個人的最小值行。SQL:根據多組最小值選擇多列?

我想要的效果就好像我將這個查詢封裝在一個循環中的一個ID集合上,然後執行每個ID爲b.id = value的查詢,但那會是(數十?)數以千計的查詢。


select top 1 a.id, b.id, a.time_point, b.time_point 
from orientation_momentum a, orientation_momentum b 
where a.id = '00820001001' and b.id = '00825001001' 
order by calculatedValue() asc 

這是在sql服務器上,但如果可能的話我更喜歡便攜式解決方案。

回答

1

SQL Server排名函數應該有所斬獲。

select * from (
select a.id, b.id, a.time_point, b.time_point, 
rank() over (partition by a.id, b.id 
order by calculatedValue() asc) ranker 
from orientation_momentum a, orientation_momentum b 
where a.id = '00820001001' and b.id between 10 and 20 
) Z where ranker = 1 
+0

謝謝,這就是我一直在尋找的。值得注意的是,這些列需要重新命名,否則會出現諸如Z'多次指定'column'id'的錯誤。 – asm