| | 1 | = Each product's monthly sales |
| | 2 | {{{#!sql |
| | 3 | CREATE OR REPLACE FUNCTION get_products_monthly_sales() |
| | 4 | RETURNS TABLE ( |
| | 5 | product_code INT, |
| | 6 | product_description TEXT, |
| | 7 | year INT, |
| | 8 | month INT, |
| | 9 | number_of_orders BIGINT, |
| | 10 | total_quantity_sold BIGINT, |
| | 11 | total_revenue NUMERIC |
| | 12 | ) |
| | 13 | LANGUAGE plpgsql |
| | 14 | AS $$ |
| | 15 | BEGIN |
| | 16 | RETURN QUERY |
| | 17 | SELECT |
| | 18 | p.code AS product_code, |
| | 19 | p.description AS product_description, |
| | 20 | EXTRACT(YEAR FROM o.last_modified_date)::INT AS year, |
| | 21 | EXTRACT(MONTH FROM o.last_modified_date)::INT AS month, |
| | 22 | COUNT(DISTINCT o.order_num) AS number_of_orders, |
| | 23 | SUM(o.quantity) AS total_quantity_sold, |
| | 24 | SUM( |
| | 25 | p.price |
| | 26 | * o.quantity |
| | 27 | * (1 - COALESCE(o.discount, 0) / 100.0) |
| | 28 | ) AS total_revenue |
| | 29 | FROM product p |
| | 30 | JOIN includes i |
| | 31 | ON p.code = i.code |
| | 32 | JOIN "order" o |
| | 33 | ON i.order_num = o.order_num |
| | 34 | GROUP BY |
| | 35 | p.code, |
| | 36 | p.description, |
| | 37 | EXTRACT(YEAR FROM o.last_modified_date), |
| | 38 | EXTRACT(MONTH FROM o.last_modified_date) |
| | 39 | ORDER BY |
| | 40 | year DESC, |
| | 41 | month DESC, |
| | 42 | total_revenue DESC; |
| | 43 | END; |
| | 44 | $$; |
| | 45 | |
| | 46 | }}} |
| | 47 | |
| | 48 | == Relational Algebra |
| | 49 | - P(code, price, availability, description, ...) |
| | 50 | - O(order_num, quantity, status, last_modified_date, payment_method, discount) |
| | 51 | - I(code, order_num) |
| | 52 | |
| | 53 | **JOIN products with orders:** |
| | 54 | - J1 ← P ⟕P.code = I.code I |
| | 55 | - J2 ← J1 ⟕I.order_num = O.order_num O |
| | 56 | |
| | 57 | **Extract year and month:** |
| | 58 | - D ← πcode, description, price, order_num, quantity, |
| | 59 | discount, |
| | 60 | YEAR(last_modified_date) → year, |
| | 61 | MONTH(last_modified_date) → month |
| | 62 | (J2) |
| | 63 | |
| | 64 | **Calculate revenue for each induvidual order:** |
| | 65 | - **FORMULA:** order_revenue = price × quantity × (1 - COALESCE(discount, 0) / 100) |
| | 66 | - R1 ← πcode, description, year, month, |
| | 67 | order_num, quantity, |
| | 68 | price × quantity × |
| | 69 | (1 - COALESCE(discount, 0) / 100) |
| | 70 | → order_revenue(D) |
| | 71 | |
| | 72 | **Agregate monthly sales:** |
| | 73 | - R2 ← γcode, description, year, month; |
| | 74 | COUNT(DISTINCT order_num) → number_of_orders, |
| | 75 | Σ(quantity) → total_quantity_sold, |
| | 76 | Σ(order_revenue) → total_revenue |
| | 77 | (R1) |
| | 78 | |
| | 79 | |
| | 80 | **Sort by total revenue:** |
| | 81 | - R_final ← τyear DESC, month DESC, total_revenue DESC(R2) |
| | 82 | |
| | 83 | |