| | 1 | = List of products who have not been ordered |
| | 2 | {{{#!sql |
| | 3 | CREATE OR REPLACE FUNCTION get_products_by_total_sales() |
| | 4 | RETURNS TABLE ( |
| | 5 | product_code INT, |
| | 6 | product_description TEXT, |
| | 7 | product_price NUMERIC, |
| | 8 | number_of_orders BIGINT, |
| | 9 | total_revenue NUMERIC |
| | 10 | ) |
| | 11 | LANGUAGE plpgsql |
| | 12 | AS $$ |
| | 13 | BEGIN |
| | 14 | RETURN QUERY |
| | 15 | SELECT |
| | 16 | p.code AS product_code, |
| | 17 | p.description AS product_description, |
| | 18 | p.price AS product_price, |
| | 19 | COUNT(DISTINCT o.order_num) AS number_of_orders, |
| | 20 | COALESCE( |
| | 21 | SUM( |
| | 22 | p.price |
| | 23 | * o.quantity |
| | 24 | * (1 - COALESCE(o.discount, 0) / 100.0) |
| | 25 | ), |
| | 26 | 0 |
| | 27 | ) AS total_revenue |
| | 28 | FROM product p |
| | 29 | LEFT JOIN includes i |
| | 30 | ON p.code = i.code |
| | 31 | LEFT JOIN "order" o |
| | 32 | ON i.order_num = o.order_num |
| | 33 | GROUP BY |
| | 34 | p.code, |
| | 35 | p.description, |
| | 36 | p.price |
| | 37 | ORDER BY |
| | 38 | number_of_orders DESC, |
| | 39 | total_revenue DESC; |
| | 40 | END; |
| | 41 | $$; |
| | 42 | CREATE OR REPLACE FUNCTION get_products_never_ordered() |
| | 43 | RETURNS TABLE ( |
| | 44 | product_code INT, |
| | 45 | product_description TEXT, |
| | 46 | product_price NUMERIC, |
| | 47 | current_stock INT |
| | 48 | ) |
| | 49 | LANGUAGE plpgsql |
| | 50 | AS $$ |
| | 51 | BEGIN |
| | 52 | RETURN QUERY |
| | 53 | SELECT |
| | 54 | p.code AS product_code, |
| | 55 | p.description AS product_description, |
| | 56 | p.price AS product_price, |
| | 57 | p.availability AS current_stock |
| | 58 | FROM product p |
| | 59 | LEFT JOIN includes i |
| | 60 | ON p.code = i.code |
| | 61 | WHERE i.order_num IS NULL |
| | 62 | ORDER BY p.code; |
| | 63 | END; |
| | 64 | $$; |
| | 65 | }}} |
| | 66 | |
| | 67 | == Relational Algebra |
| | 68 | - P(code, price, availability, description, ...) |
| | 69 | - I(code, order_num) |
| | 70 | |
| | 71 | **JOIN products with orders:** |
| | 72 | - J1 ← P ⟕P.code = I.code I |
| | 73 | - J2 ← J1 ⟕I.order_num = O.order_num O |
| | 74 | |
| | 75 | **FILTER products that haven't been ordered yet:** |
| | 76 | - R ← σorder_num IS NULL(J1) |
| | 77 | |
| | 78 | **Sort by product code:** |
| | 79 | - R_final ← τcode ASC(R) |
| | 80 | |
| | 81 | |