gpt4 book ai didi

sql - 如何使用窗口函数获取最高价格及其 ID?

转载 作者:行者123 更新时间:2023-12-04 14:19:18 24 4
gpt4 key购买 nike

我有这个问题

select adate, factoryid, purchid, itemname, max(price) as price 
from tableb where catnum = 9
group by adate, factoryid, purchid, itemname
order by adate, factoryid, purchid, itemname

但我想要该行的 ID。所以在一个完美的世界中:

select id, adate, factoryid, purchid, itemname, max(price) as price 
from tableb where catnum = 9
group by adate, factoryid, purchid, itemname
order by adate, factoryid, purchid, itemname

但我知道那是行不通的。

所以我尝试了这个:

select id, adate, factoryid, purchid, itemname, 
max(price) over(partition by adate, factoryid, purchid, itemname) as price
from tableb where catnum = 9

那是行不通的。所有 ID 的价格都是重复的。查询结果集从 4000 行增加到 11000 行。

很明显,我以某种方式弄错了窗口函数。首先,我做错了什么,其次,当然,我该如何解决?

最佳答案

SELECT  *
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY adate, factoryid, purchid, itemname ORDER BY price DESC, id DESC) rn
FROM tableb
WHERE catnum = 9
) q
WHERE rn = 1

关于sql - 如何使用窗口函数获取最高价格及其 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31171998/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com