diff --git a/aharlamcev/postgresql/WindowFunctionHomework.sql b/aharlamcev/postgresql/WindowFunctionHomework.sql index bd81ac9..0e16bf1 100644 --- a/aharlamcev/postgresql/WindowFunctionHomework.sql +++ b/aharlamcev/postgresql/WindowFunctionHomework.sql @@ -22,21 +22,51 @@ values (1, 'iPhone 14', 'smartphone', 799, true, 'iphone@apple.com'), alter table products_extended alter column price type DECIMAL(10, 2) -select * from products_extended - +------------------ Задание №1 (По нему ты говорил, что нечитаемо, объясни как переделать pls <3) with email_false as (select * 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) where rn = 1 +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) +where rn = 1 ), email_true as (select * 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) where rn = 1 +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) +where rn = 1 ) select category, name, price, email_support from email_false union all select category, name, price, email_support from email_true order by category, price desc + +---------------------- Задание №2 (Переделал с двух оконок в одном запросе на СТЕ с одной оконкой внутри) +with get_data as ( +select name, category, price, +LEAD(price) OVER (PARTITION BY category order by price) AS next_price +from products_extended +) + +select name, category, price, next_price, +price - next_price AS diff +from get_data + +--------------------- Задание №3 +select category, name, price, +SUM(price) over (partition by category order by price) as cumulative_sales +from products_extended + +---------------------- Задание №4 +with get_data as ( +select category, name, price, AVG(price) over (partition by category) as avg_price +from products_extended +) +select category, name, price, avg_price, +case when price > avg_price then 'true' else 'false' end as is_above_avg +from get_data