我的SQL代码如下:
Select Model,Max(Price) FROM Printer GROUP BY Model ORDER BY Max(Price) DESC;
它应该返回以下内容:
MODEL MAX PRICE
3007 899
3003 899
但是,它会返回:
MODEL MAX PRICE
3007 899
3003 899
3002 139
3004 120
3006 100
3005 99
我做错了什么?我尝试更改或删除Order by等,但它并没有解决我的问题。
答案 0 :(得分:1)
如果您只想要最高价格的行,那么您需要限制行数。您似乎想要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;
答案 1 :(得分:1)
这是一种更清洁的方法来获得我想要的东西
SELECT
Model,
Price
FROM
Printer
WHERE price = (SELECT MAX(PRICE) FROM Printer)
;
答案 2 :(得分:1)
如果您使用的是Oracle 12.1或更高版本:
select model, max(price) from printer
group by model
order by max(price) desc
fetch first row with ties;