2016-05-26 55 views
0

我有一個3列SQL查詢來選擇與最大和最小NID值的另一行

nid aid cst 
1 1 23 
2 3 45 
3 1 67 
4 2 34 
5 3 12 
6 1 6 

請重讀解釋: 我一定要找到助劑,它具有NID的最小值的CST例如,當我選擇aid = 1時,它必須給出23作爲 它相當於 nid(1)的最小值,當我選擇3時它必須給出45,因爲它至少有nid(2),與其他所有nid援助

我的這次嘗試是不行的:

select cst from tbl 
where (nid) IN (select min(nid) from tbl) and aid=nid 

我也必須做最大的一樣,因爲我做了最小。

+0

SELECT FIRST_VALUE(CST)OVER(ORDER BY NID),LAST_VALUE(CST)的所有值(ORDER BY NID) WHERE aid = @aid – adrianm

+0

什麼是我必須得到所有cst相應的aid = 1? –

回答

0
select cst 
from tbl 
where aid=1 and nid=(select min(nid) from tbl where aid=1) 

這個查詢會給你的cst最小值及由TBL aid

+0

請重新讀取有問題的問題有混淆 –

+0

檢查更新的查詢 –

+0

我得到什麼所有的cst相應的援助= 1? –

0

一種方法是使用row_number()

select t.* 
from (select t.*, row_number() over (partition by aid order by cst) as seqnum 
     from tbl t 
    ) t 
where seqnum = 1; 

你的方法將與表的別名,限定列名,和正確的邏輯工作:

select t.cst 
from tbl t 
where t.cst = (select min(t2.cst) from tbl t2 where t2.aid = t.aid); 

或者更簡單地說:

select aid, min(cst) 
from t 
group by aid; 
+0

我必須處理最小和最大 –

+0

有沒有T2表...只有一個表 –

+0

請重新讀取的問題有混亂 –

0
select cst from tbl_NID where aid =1 and nid in (select min (nid) from tbl_NID where aid=1 ) 

select cst from tbl_NID where aid =1 and nid like (select min (nid) from tbl_NID where aid=1 ) 

Example Query

+0

我得到的所有cst對應aid = 1是什麼? –

+0

它是示例查詢,你可以把你的價值 – SK2185