Files
homework/avysokih/postgresql/window functions/win_func_tasks.sql
T
2026-01-15 19:20:41 +03:00

81 lines
2.2 KiB
SQL
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
Задача 1:
Для каждой категории показать 2 строки:
- Самый дорогой товар с email'ом
- Самый дорогой товар без email'а
*/
with with_mail as (
select category, name, price, email_support
from (
select category, name, price, email_support,
row_number() over (partition by category order by price desc) as rn
from products_extended
where email_support is not null
) t
where rn = 1
),
without_mail as (
select category, name, price, email_support
from (
select category, name, price, email_support,
row_number() over (partition by category order by price desc) as rn
from products_extended
where email_support is null
) t
where rn = 1
)
select * from with_mail
union all
select * from without_mail
order by category;
/*
Задача 2:
Для каждого товара показать:
- `name` — название товара
- `category` — категория товара
- `price` — цена текущего товара
- `next_price` — цена следующего товара внутри той же категории, упорядоченного по цене
- `diff` — разница между ценой текущего товара и ценой следующего товара
(`price - next_price`)
*/
select name, category, price, lead(price) over(partition by category order by price) as next_price,
price - lead(price) over(partition by category order by price) as diff
from products_extended;
/*
Задача 3:
Показать `category`, `name`, `price`, `cumulative_sales`
Где `cumulative_sales` — это сумма `price` **внутри категории** по мере возрастания цены
*/
select category, name, price,
sum(price) over (partition by category order by price) as cumulative_sales
from products_extended;
/*
Задача 4:
Вывести `category`, `name`, `price`, `avg_price`, `is_above_avg`
Где `avg_price` — средняя цена по категории
`is_above_avg = true`, если `price > avg_price`
*/
select category, name, price,
round(avg(price) over (partition by category), 1) as avg_price,
price > avg(price) over (partition by category) as is_above_avg
from products_extended;