SQL语句,仅选择其中一列中包含最大值的行

时间:2014-11-12 22:48:29

标签: sql sql-server tsql

我有下表:

select * from [Auction].[dbo].[Bids]

enter image description here

我需要选择BidValue最高的行。当我做的时候

SELECT bids.itemId, max(bids.[bidValue]) as HighestBid
FROM [Auction].[dbo].[Bids] bids
WHERE bids.itemId = 2
GROUP BY bids.itemId

我得到了正确的一行:

enter image description here

...但是当我添加另外两个字段时它不起作用(我知道它因为Group by而显示3行,但是如果我不在组中包含这些字段则会引发错误由):

SELECT bids.itemId, max(bids.[bidValue]) as HighestBid, bids.submittedBy, bids.submittedOn
FROM [Auction].[dbo].[Bids] bids
WHERE bids.itemId = 2
GROUP BY bids.itemId, bids.submittedBy, bids.submittedOn

enter image description here

所以,我需要它用itemId,HighestBid,submittedBy和submittedOn显示一行。

感谢任何帮助!

3 个答案:

答案 0 :(得分:2)

您可以这样做:

select TOP 1 * from Bids where ItemId = 2 order by BidValue desc

答案 1 :(得分:0)

试试这个

select top 1 * from Bids order by BidValue desc

答案 2 :(得分:0)

如果超过一个最高值则使用

select TOP (1) with ties * 
from Bids where ItemId = 2 order by BidValue desc