From 761578c56ea527cacc3d84e06758d64c909e9eff Mon Sep 17 00:00:00 2001 From: plidan123 Date: Thu, 25 Sep 2025 18:39:21 +0300 Subject: [PATCH 1/2] =?UTF-8?q?=D0=B4=D0=B7=203?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hws/hw_3.sql | 198 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 198 insertions(+) create mode 100644 hws/hw_3.sql diff --git a/hws/hw_3.sql b/hws/hw_3.sql new file mode 100644 index 0000000..5c36a88 --- /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 all +(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 ) +--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 categoryname,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 categoryname,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 categoryname,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 categoryname,unitprice +limit 2) +--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) +union +(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) +union +(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') +union +(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 выбирает наиболее эффективный +-- план независимо от исходного порядка таблиц. + + From 72ae822572160b11b1c25d3a2aa6c88d1311ce79 Mon Sep 17 00:00:00 2001 From: plidan123 Date: Sat, 20 Dec 2025 04:31:23 +0300 Subject: [PATCH 2/2] Update hw_3.sql --- hws/hw_3.sql | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/hws/hw_3.sql b/hws/hw_3.sql index 5c36a88..9fbb154 100644 --- a/hws/hw_3.sql +++ b/hws/hw_3.sql @@ -6,21 +6,22 @@ join "Sales"."Orders" as o on o.custid=c.custid where c.custid=1 order by o.orderdate asc limit 2 ) -union all +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 +((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 categoryname,unitprice +order by p.unitprice limit 2) union all (select btrim(split_part(companyname, ' ',2)), productname, unitprice,categoryname @@ -28,7 +29,7 @@ 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 categoryname,unitprice +order by p.unitprice limit 2) union all (select btrim(split_part(companyname, ' ',2)), productname, unitprice,categoryname @@ -36,7 +37,7 @@ 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 categoryname,unitprice +order by p.unitprice limit 2) union all (select btrim(split_part(companyname, ' ',2)), productname, unitprice,categoryname @@ -44,8 +45,9 @@ 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 categoryname,unitprice -limit 2) +order by p.unitprice +limit 2)) +order by categoryname asc, unitprice desc; --3. Сформируйте 2 выборки следующего вида: --a. В первом случае, выборка должна содержать список продуктов, которые входили в «корзину» --первого покупателя (custid=1) и точно не входили в объединенные корзины 2 и 3 покупателей @@ -81,7 +83,7 @@ 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 +intersect (select productname,p.unitprice, categoryname from "Sales"."Customers" as c join "Sales"."Orders" as o on c.custid=o.custid @@ -89,7 +91,7 @@ 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) -union +intersect (select productname,p.unitprice, categoryname from "Sales"."Customers" as c join "Sales"."Orders" as o on c.custid=o.custid @@ -118,7 +120,7 @@ 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') -union +intersect (select distinct o.empid, o.custid from "HR"."Employees" as e join "Sales"."Orders" as o on o.empid=e.empid @@ -194,5 +196,3 @@ join "Production"."Categories" c on c.categoryid = p.categoryid; --оптимизатор рассматривает разные комбинации соединений. Однако на фактическое время выполнения --(Execution Time) порядок таблиц практически не влияет, так как PostgreSQL выбирает наиболее эффективный -- план независимо от исходного порядка таблиц. - -