I have a table with columns: unique_id, product, root_location, price
with more than 50 million records
I want the result to be product, min_price, min_price_unique_id, max_price, max_price_unique_id
My query:
select product
, min(price) as min_price
, max(price) as max_price
from mytable
group by product
How to get the unique id's of min and max price?
3条答案
按热度按时间t9aqgxwy1#
You could try using
RANK
andSTRING_AGG
with conditional aggregation as the following:demo
Update: To get the unique
donator_ids
values in case duplicates have existed, you could use another subquery/ CTE, and use the row_number function partitioned by product, unique_id then get only rows where row_number =1.demo
y4ekin9u2#
This query uses two joins to the original table
mytable
to get the unique ids of the minimum and maximum prices. 1. The subquery calculates the max and min price for each product and the subquerya
is joined with the original tablemytable
twice. Once to get the unique id of the minimum price and then to get the unique id of the maximum price. The join condition for both joins is the price column.db<>fiddle
qfe3c7zg3#
It really depends on what you want with the
unique_id
. In the situation where there are multipleunique_id
for themin
ormax
price, do you want to return allunique_id
or just only one.Depending on your requirement, use
row_number()
ordense_rank()
. Do check out the documentation for the details on these 2 window functions.Below query will return One
unique_id
perproduct
.Edit : if you do want to show all the corresponding
unique_id
for the min and max price, here is one way. Use 2 separate query to identify the min and max price after that join usingfull outer join
(as there might be different number ofunique_id
rows in the min or max price)