简体   繁体   English

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

[英]SQL statement to select only row containing max value in one of the columns

I have the following table: 我有下表:

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

在此处输入图片说明

I need to select a row with the highest BidValue. 我需要选择具有最高BidValue的行。 When I do 当我做

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

I get the right row: 我得到正确的行:

在此处输入图片说明

... but when I add two other fields it doesn't work (I know it shows 3 rows because of the Group by, but it throws an error if I don't include those fields in group by): ...但是当我添加其他两个字段时,它不起作用(我知道由于Group by会显示3行,但是如果我在group by中不包含这些字段,则会引发错误):

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

在此处输入图片说明

So, I need it do display one row with itemId, HighestBid, submittedBy, and submittedOn. 因此,我需要用itemId,HighestBid,submittedBy和SubmittedOn显示一行。

Any help is appreciated! 任何帮助表示赞赏!

您可以简单地执行以下操作:

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

尝试这个

select top 1 * from Bids order by BidValue desc

if more then one highest value then use 如果多于一个最大值,则使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM