我需要从表中获取最大行数

问题描述 投票:0回答:3

我有这样的表:

id | idx | cost
1    1     500
2    1     1000
3    2     500
4    2     9000

我需要得到最大cost id=@id

所以我写了这个查询:

SELECT   Id
FROM    table
WHERE (cost= (SELECT MAX(cost) AS Expr1 FROM  table AS table_1)) AND (idx= @idx)

但这仅适用于费用最高的所有费用

我需要获得idx=@idx最大成本的id

sql
3个回答
2
投票

使用top (1)条款:

select top (1) t.*
from table t
where idx = @id
order by cost desc;

1
投票

只需使用order by和某些东西限制为一行:

select t.*
from t
where id = @id
order by cost desc
fetch first 1 row only;

0
投票

用这个:

SELECT * FROM table WHERE idx = @idx AND cost = (SELECT MAX(cost) FROM table WHERE idx = @idx);

© www.soinside.com 2019 - 2024. All rights reserved.