SQL查询以选择具有最小和最大nid值的另一行

时间:2016-05-26 12:05:09

标签: sql .net sql-server

我有3列

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相比,nid(2)最少

我尝试这个广告不起作用:

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

我也必须像我为min做的那样做最多。

3 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

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

此查询将为cst

的所有值提供aid的最小值

答案 2 :(得分: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