Выведите самую дорогую и дешевую покупку:
SELECT PIP.purchase_id, SUM(PIP.product_count * PR.new_price) AS all_sum
FROM product_in_purchase AS PIP
RIGHT OUTER JOIN price_register AS PR ON PIP.product_id = PR.product_id
GROUP BY PIP.purchase_id
ORDER BY SUM(PIP.product_count * PR.new_price) DESC LIMIT 1
UNION [ALL]
SELECT PIP.purchase_id, SUM(PIP.product_count * PR.new_price) AS all_sum
FROM product_in_purchase AS PIP
RIGHT OUTER JOIN price_register AS PR ON PIP.product_id = PR.product_id
GROUP BY PIP.purchase_id
ORDER BY SUM(PIP.product_count * PR.new_price) LIMIT 1;
Может, подскажите, как корректнее построить запрос?
Есть что-то такое, но из-за полей в БД это решение не подходит:
SELECT
res.purchase_id,
res.rnk_max,
res.rnk_min
FROM (
SELECT
pp.purchase_id,
DENSE_RANK() OVER(ORDER BY pp.product_price * pp.product_count DESC) AS rnk_max,
DENSE_RANK() OVER(ORDER BY pp.product_price * pp.product_count) AS rnk_min
FROM public."Product_In_Purchase" AS pp
) AS res
WHERE res.rnk_max = 1 OR res.rnk_min = 1
Вот поля в таблицах: