diff --git a/hws/hw_3.sql b/hws/hw_3.sql new file mode 100644 index 0000000..9fbb154 --- /dev/null +++ b/hws/hw_3.sql @@ -0,0 +1,198 @@ +--Задание 1. Использование операторов наборов записей (UNION, EXCEPT, INTERSECT) +--1. Выведите 2 самых первых заказа сделанных первым заказчиком (custid=1) и 2 самых последних его заказа. Выборка должна быть упорядочена по годам и месяцам +(select btrim(split_part(c.companyname,' ',2)), orderid , to_char(orderdate, 'MM-YYYY') AS "month-year" +from "Sales"."Customers" as c +join "Sales"."Orders" as o on o.custid=c.custid +where c.custid=1 +order by o.orderdate asc +limit 2 ) +union +(select btrim(split_part(c.companyname,' ',2)), orderid , to_char(orderdate, 'MM-YYYY') AS "month-year" +from "Sales"."Customers" as c +join "Sales"."Orders" as o on o.custid=c.custid +where c.custid=1 +order by o.orderdate desc +limit 2 ) +order by orderid; +--2. Выведите по 2 самых дешевых продукта каждого поставщика из списка (2, 5, 15, 25). +--Выборка должна быть упорядочена по категории и цене. +((select btrim(split_part(companyname, ' ',2)), productname, unitprice,categoryname +from "Production"."Suppliers" as s +join "Production"."Products" as p on p.supplierid=s.supplierid +join "Production"."Categories" as c on p.categoryid=c.categoryid +where s.supplierid = 2 +order by p.unitprice +limit 2) +union all +(select btrim(split_part(companyname, ' ',2)), productname, unitprice,categoryname +from "Production"."Suppliers" as s +join "Production"."Products" as p on p.supplierid=s.supplierid +join "Production"."Categories" as c on p.categoryid=c.categoryid +where s.supplierid = 5 +order by p.unitprice +limit 2) +union all +(select btrim(split_part(companyname, ' ',2)), productname, unitprice,categoryname +from "Production"."Suppliers" as s +join "Production"."Products" as p on p.supplierid=s.supplierid +join "Production"."Categories" as c on p.categoryid=c.categoryid +where s.supplierid = 15 +order by p.unitprice +limit 2) +union all +(select btrim(split_part(companyname, ' ',2)), productname, unitprice,categoryname +from "Production"."Suppliers" as s +join "Production"."Products" as p on p.supplierid=s.supplierid +join "Production"."Categories" as c on p.categoryid=c.categoryid +where s.supplierid = 25 +order by p.unitprice +limit 2)) +order by categoryname asc, unitprice desc; +--3. Сформируйте 2 выборки следующего вида: +--a. В первом случае, выборка должна содержать список продуктов, которые входили в «корзину» +--первого покупателя (custid=1) и точно не входили в объединенные корзины 2 и 3 покупателей +(select productname,p.unitprice, categoryname +from "Sales"."Customers" as c +join "Sales"."Orders" as o on c.custid=o.custid +join "Sales"."OrderDetails" as od on od.orderid=o.orderid +join "Production"."Products" as p on p.productid=od.productid +join "Production"."Categories" as cat on cat.categoryid = p.categoryid +where c.custid=1) +except +((select productname,p.unitprice, categoryname +from "Sales"."Customers" as c +join "Sales"."Orders" as o on c.custid=o.custid +join "Sales"."OrderDetails" as od on od.orderid=o.orderid +join "Production"."Products" as p on p.productid=od.productid +join "Production"."Categories" as cat on cat.categoryid = p.categoryid +where c.custid=2) +union all +(select productname,p.unitprice, categoryname +from "Sales"."Customers" as c +join "Sales"."Orders" as o on c.custid=o.custid +join "Sales"."OrderDetails" as od on od.orderid=o.orderid +join "Production"."Products" as p on p.productid=od.productid +join "Production"."Categories" as cat on cat.categoryid = p.categoryid +where c.custid=3)) +--b. Во втором случае, выборка должна включать только те продукты, которые присутствуют в +--продуктовых «корзинах» покупателей 2, 3 и 14 +(select productname,p.unitprice, categoryname +from "Sales"."Customers" as c +join "Sales"."Orders" as o on c.custid=o.custid +join "Sales"."OrderDetails" as od on od.orderid=o.orderid +join "Production"."Products" as p on p.productid=od.productid +join "Production"."Categories" as cat on cat.categoryid = p.categoryid +where c.custid=2) +intersect +(select productname,p.unitprice, categoryname +from "Sales"."Customers" as c +join "Sales"."Orders" as o on c.custid=o.custid +join "Sales"."OrderDetails" as od on od.orderid=o.orderid +join "Production"."Products" as p on p.productid=od.productid +join "Production"."Categories" as cat on cat.categoryid = p.categoryid +where c.custid=3) +intersect +(select productname,p.unitprice, categoryname +from "Sales"."Customers" as c +join "Sales"."Orders" as o on c.custid=o.custid +join "Sales"."OrderDetails" as od on od.orderid=o.orderid +join "Production"."Products" as p on p.productid=od.productid +join "Production"."Categories" as cat on cat.categoryid = p.categoryid +where c.custid=14) +--4. Сформируйте 2 выборки следующего вида: +-- +--a. В первом случае выборка должна включать уникальный список только тех клиентов, с которыми +--сотрудник взаимодействовал в 2008 году и точно не взаимодействовал в 2007 +(select distinct o.empid, o.custid +from "HR"."Employees" as e +join "Sales"."Orders" as o on o.empid=e.empid +join "Sales"."Customers" as c on c.custid = o.custid +where orderdate between '2008-01-01' and '2008-12-31') +except +(select distinct o.empid, o.custid +from "HR"."Employees" as e +join "Sales"."Orders" as o on o.empid=e.empid +join "Sales"."Customers" as c on c.custid = o.custid +where orderdate between '2007-01-01' and '2007-12-31') +--b. Вторая выборка должна включать уникальный список тех клиентов, с которыми сотрудник взаимодействовал и в 2008 году и в 2007 +(select distinct o.empid, o.custid +from "HR"."Employees" as e +join "Sales"."Orders" as o on o.empid=e.empid +join "Sales"."Customers" as c on c.custid = o.custid +where orderdate between '2008-01-01' and '2008-12-31') +intersect +(select distinct o.empid, o.custid +from "HR"."Employees" as e +join "Sales"."Orders" as o on o.empid=e.empid +join "Sales"."Customers" as c on c.custid = o.custid +where orderdate between '2007-01-01' and '2007-12-31') +--Задание 2. Анализ планов выполнения +--1. Проанализируйте план выполнения запроса из задания 1.3a +explain analyze (select productname,p.unitprice, categoryname +from "Sales"."Customers" as c +join "Sales"."Orders" as o on c.custid=o.custid +join "Sales"."OrderDetails" as od on od.orderid=o.orderid +join "Production"."Products" as p on p.productid=od.productid +join "Production"."Categories" as cat on cat.categoryid = p.categoryid +where c.custid=1) +except +((select productname,p.unitprice, categoryname +from "Sales"."Customers" as c +join "Sales"."Orders" as o on c.custid=o.custid +join "Sales"."OrderDetails" as od on od.orderid=o.orderid +join "Production"."Products" as p on p.productid=od.productid +join "Production"."Categories" as cat on cat.categoryid = p.categoryid +where c.custid=2) +union all +(select productname,p.unitprice, categoryname +from "Sales"."Customers" as c +join "Sales"."Orders" as o on c.custid=o.custid +join "Sales"."OrderDetails" as od on od.orderid=o.orderid +join "Production"."Products" as p on p.productid=od.productid +join "Production"."Categories" as cat on cat.categoryid = p.categoryid +where c.custid=3)) +--Planning Time: 1.324 ms +--2. Измените порядок таблиц в предложении FROM и сравните планы выполнения. +explain analyze (select productname,p.unitprice, categoryname +from "Sales"."Orders" as o +join "Sales"."Customers" as c on c.custid=o.custid +join "Sales"."OrderDetails" as od on od.orderid=o.orderid +join "Production"."Products" as p on p.productid=od.productid +join "Production"."Categories" as cat on cat.categoryid = p.categoryid +where c.custid=1) +except +((select productname,p.unitprice, categoryname +from "Sales"."Orders" as o +join "Sales"."Customers" as c on c.custid=o.custid +join "Sales"."OrderDetails" as od on od.orderid=o.orderid +join "Production"."Products" as p on p.productid=od.productid +join "Production"."Categories" as cat on cat.categoryid = p.categoryid +where c.custid=2) +union all +(select productname,p.unitprice, categoryname +from "Sales"."Orders" as o +join "Sales"."Customers" as c on c.custid=o.custid +join "Sales"."OrderDetails" as od on od.orderid=o.orderid +join "Production"."Products" as p on p.productid=od.productid +join "Production"."Categories" as cat on cat.categoryid = p.categoryid +where c.custid=3)) +--Planning Time: 1.608 ms +--3. Определите, влияет ли порядок таблиц на производительность запроса. +--Порядок таблиц в FROM влияет в основном на процесс планирования, так как оптимизатор рассматривает разные комбинации соединений. +--4. Приведите пример, объясните результат +explain analyze +select * +from "Production"."Categories" as c +join "Production"."Products" p on c.categoryid = p.categoryid; +--Planning Time: 0.161 ms +--Execution Time: 0.092 ms +explain analyze +select * +from "Production"."Products" p +join "Production"."Categories" c on c.categoryid = p.categoryid; +--Planning Time: 0.138 ms +--Execution Time: 0.081 ms +--Вывод: Порядок таблиц в предложении FROM влияет на время построения плана (Planning Time), так как +--оптимизатор рассматривает разные комбинации соединений. Однако на фактическое время выполнения +--(Execution Time) порядок таблиц практически не влияет, так как PostgreSQL выбирает наиболее эффективный +-- план независимо от исходного порядка таблиц.