Files
homework/pmikhailov/postgresql/homework-aggregation-groupby.sql
T
2026-06-06 21:45:07 +02:00

112 lines
1.9 KiB
SQL
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* Задание 1 */
SELECT
category,
count(*) AS products_count 
FROM
products p
GROUP BY category
ORDER BY products_count DESC;
/* Задание 2
* Тут всё решение в задании
* */
SELECT
order_id,
sum(quantity) AS total_quantity,
sum(quantity * price_at_purchase) AS order_revenue
FROM
order_items oi
GROUP BY order_id
ORDER BY order_revenue DESC;
/* Задание 3 */
SELECT
p.category,
COALESCE(sum(oi.quantity * oi.price_at_purchase), 0) AS category_revenue
FROM
products p
LEFT JOIN
order_items oi ON p.id = oi.product_id
GROUP BY p.category
/* Задание 4 */
SELECT
o.id AS order_id,
sum(oi.quantity * oi.price_at_purchase) AS order_revenue 
FROM
orders o
LEFT JOIN
order_items oi ON o.id = oi.order_id
WHERE o.status = 'paid'
GROUP BY 1
ORDER BY 2 DESC
/* Задание 5 */
SELECT
p.category,
COALESCE(sum(oi.quantity * oi.price_at_purchase), 0) AS category_revenue
FROM
products p
LEFT JOIN
order_items oi ON p.id = oi.product_id
GROUP BY
p.category
HAVING
sum(oi.quantity * oi.price_at_purchase) > 1;
/* Задание 6 */
SELECT
country,
count(*) AS active_users_count 
FROM
users u
WHERE
is_active = TRUE
GROUP BY
country
HAVING
count(is_active) > 2;
/* Задание 7 */
SELECT
p.name AS product_name,
COALESCE (sum(oi.quantity), 0) AS total_quantity_sold 
FROM
products p
LEFT JOIN
order_items oi ON p.id = oi.product_id
GROUP BY p.name
ORDER BY 2 DESC
LIMIT 3
/* Задание 8
* Условие для HAVING в задаче кривое, < 100 ничего нет
* */
SELECT
order_id,
SUM(quantity * price_at_purchase) AS order_revenue 
FROM
order_items oi
GROUP BY
order_id
HAVING
SUM(quantity * price_at_purchase) < 10000
ORDER BY 2;