diff --git a/avysokih/postgresql/window functions/leetcode_180_1.JPG b/avysokih/postgresql/window functions/leetcode_180_1.JPG new file mode 100644 index 0000000..af73249 Binary files /dev/null and b/avysokih/postgresql/window functions/leetcode_180_1.JPG differ diff --git a/avysokih/postgresql/window functions/leetcode_180_2.JPG b/avysokih/postgresql/window functions/leetcode_180_2.JPG new file mode 100644 index 0000000..7b3587e Binary files /dev/null and b/avysokih/postgresql/window functions/leetcode_180_2.JPG differ diff --git a/avysokih/postgresql/window functions/win_func_tasks.sql b/avysokih/postgresql/window functions/win_func_tasks.sql new file mode 100644 index 0000000..f3a3e5d --- /dev/null +++ b/avysokih/postgresql/window functions/win_func_tasks.sql @@ -0,0 +1,80 @@ +/* +Задача 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; + + +