我有这样的表:
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
使用top (1)
条款:
select top (1) t.*
from table t
where idx = @id
order by cost desc;
只需使用order by
和某些东西限制为一行:
select t.*
from t
where id = @id
order by cost desc
fetch first 1 row only;
用这个:
SELECT * FROM table WHERE idx = @idx AND cost = (SELECT MAX(cost) FROM table WHERE idx = @idx);