简体   繁体   English

SQL:最大值未选择最大值

[英]SQL: Max Value is not selecting the Max

My SQL Code is the following: 我的SQL代码如下:

Select Model,Max(Price) FROM Printer GROUP BY Model ORDER BY Max(Price) DESC;

It should return the following: 它应该返回以下内容:

MODEL   MAX PRICE
3007    899
3003    899

However, it instead returns this: 但是,它返回以下内容:

MODEL   MAX PRICE
3007    899
3003    899
3002    139
3004    120
3006    100
3005    99

What am I doing wrong? 我究竟做错了什么? I tried changing or removing Order by and the like, but it did not fix my problem. 我尝试更改或删除Order by等类似方法,但是并没有解决我的问题。

If you only want the maximum priced rows, then you need to limit the number of rows. 如果您只想要定价最高的行,则需要限制行数。 You seem to want rank() : 您似乎想要rank()

SELECT Model, max_price
FROM (SELECT Model, MAX(Price) as max_price,
             RANK() OVER (ORDER BY MAX(PRICE) DESC NULLS LAST) as seqnum
      FROM Printer p
      GROUP BY Model
     ) p
WHERE seqnum = 1;

This is a cleaner method to get what I wanted 这是一种获取我想要的清洁方法

SELECT 
Model, 
Price
FROM
Printer
WHERE price = (SELECT MAX(PRICE) FROM Printer)
;

If you are using Oracle 12.1 or later: 如果您使用的是Oracle 12.1或更高版本:

select model, max(price) from printer
group by model
order by max(price) desc
fetch first row with ties;

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

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