73 lines
2.5 KiB
SQL
73 lines
2.5 KiB
SQL
create table products_extended (
|
|
id INT primary key,
|
|
name VARCHAR(50) not null,
|
|
category VARCHAR(50) not null,
|
|
price INT,
|
|
in_stock BOOLEAN default true,
|
|
email_support VARCHAR(50)
|
|
);
|
|
|
|
insert into products_extended (id, name, category, price, in_stock, email_support)
|
|
values (1, 'iPhone 14', 'smartphone', 799, true, 'iphone@apple.com'),
|
|
(2, 'MacBook Air', 'laptop', 1199, false, NULL),
|
|
(3, 'Galaxy S22', 'smartphone', 699, true, 'galaxy@support.com'),
|
|
(4, 'ThinkPad X1', 'laptop', 1399, true, 'thinkpad@lenovo.com'),
|
|
(5, 'iPad Pro', 'tablet', 999, false, 'ipad@apple.com'),
|
|
(6, 'Kindle Paperwhite', 'ebook_reader', 149, true, NULL),
|
|
(7, 'Mi Band 7', 'smartwatch', 49, true, 'miband@xiaomi.com'),
|
|
(8, 'Surface Pro', 'tablet', 1299, true, 'surface@microsoft.com'),
|
|
(9, 'Honor Pad X9', 'tablet', 219, true, 'honor@support.com'),
|
|
(10, 'Dell XPS 13', 'laptop', 1099, false, 'dell@support.com');
|
|
|
|
alter table products_extended
|
|
alter column price type DECIMAL(10, 2)
|
|
|
|
------------------ Задание №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
|
|
),
|
|
|
|
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 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
|