简体   繁体   中英

SQL Max of a sum (two rows with same value)

So, I had a quiz with the question being to write a select query that returns the highest valued items (and only the highest). So I have 2 tables one with the inventory of items, one with their prices of each items. I had to sum the value of all the items and then return which items had the most value, and if any had the same to show both.

What I came up with works, but i'm fairly positive there's a simpler way to do that. I was just wondering if someone could help me simplify my answer:

select a.item from
(select item , sum(price) as price from Inventory i
inner join prices p on p.item = i.item
group by item, price) a
where price= (select MAX(a.price) from
(select item , sum(price) as price from Inventory i
inner join prices p on p.item = i.item
group by item, price) a)

You could write (using the HAVING function)

select i.item
from Inventory i
inner join prices p on p.item = i.item
group by i.item
having sum(price) = (SELECT MAX(sum_price) from (select SUM(price) OVER (PARTITION BY item) sum_price from prices) a);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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