Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use window function to get max price and its id?

I have this query

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

But I want the id for that row. So in a perfect world:

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

But I know that won't work.

So I tried this:

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

That doesn't work. The price is duplicated for all the ids. And the query result set goes from 4000 rows to 11000.

So obviously, I got the window function wrong somehow. First what did I do wrong and secondly, of course, how do I fix it?

like image 895
dotnetN00b Avatar asked Nov 26 '25 20:11

dotnetN00b


1 Answers

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
like image 165
Quassnoi Avatar answered Nov 29 '25 10:11

Quassnoi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!