| | 1 | = Orders ordered by order total from highest to lowest |
| | 2 | {{{#!sql |
| | 3 | CREATE OR REPLACE FUNCTION get_orders_by_total() |
| | 4 | RETURNS TABLE ( |
| | 5 | order_num INT, |
| | 6 | client_id INT, |
| | 7 | client_name TEXT, |
| | 8 | order_quantity INT, |
| | 9 | order_status TEXT, |
| | 10 | payment_method TEXT, |
| | 11 | discount NUMERIC, |
| | 12 | order_total NUMERIC |
| | 13 | ) |
| | 14 | LANGUAGE plpgsql |
| | 15 | AS $$ |
| | 16 | BEGIN |
| | 17 | RETURN QUERY |
| | 18 | SELECT |
| | 19 | o.order_num, |
| | 20 | c.client_id, |
| | 21 | c.name, |
| | 22 | o.quantity, |
| | 23 | o.status, |
| | 24 | o.payment_method, |
| | 25 | COALESCE(o.discount, 0) AS discount, |
| | 26 | SUM(p.price * o.quantity) |
| | 27 | * (1 - COALESCE(o.discount, 0) / 100) AS order_total |
| | 28 | FROM "order" o |
| | 29 | JOIN makes_order mo |
| | 30 | ON o.order_num = mo.order_num |
| | 31 | JOIN client c |
| | 32 | ON mo.client_id = c.client_id |
| | 33 | JOIN includes i |
| | 34 | ON o.order_num = i.order_num |
| | 35 | JOIN product p |
| | 36 | ON i.code = p.code |
| | 37 | GROUP BY |
| | 38 | o.order_num, |
| | 39 | c.client_id, |
| | 40 | c.name, |
| | 41 | o.quantity, |
| | 42 | o.status, |
| | 43 | o.payment_method, |
| | 44 | o.discount |
| | 45 | ORDER BY order_total DESC; |
| | 46 | END; |
| | 47 | $$; |
| | 48 | |
| | 49 | }}} |
| | 50 | |
| | 51 | == Relational Algebra |
| | 52 | - P(code, price, availability, description, ...) |
| | 53 | - O(order_num, quantity, status, last_modified_date, payment_method, discount) |
| | 54 | - I(code, order_num) |
| | 55 | - MO(client_id, order_num) |
| | 56 | - C(client_id, name, first_name, last_name, ...) |
| | 57 | |
| | 58 | **JOIN orders with client lists:** |
| | 59 | - J1 ← O ⨝O.order_num = MO.order_num MO |
| | 60 | - J2 ← J1 ⨝MO.client_id = C.client_id C |
| | 61 | |
| | 62 | **JOIN orders with their included products:** |
| | 63 | - J3 ← J2 ⨝O.order_num = I.order_num I |
| | 64 | - J4 ← J3 ⨝I.code = P.code P |
| | 65 | |
| | 66 | **Calculate the total order value:** |
| | 67 | - **FORMULA:** order_total = Σ(P.price × O.quantity) × (1 - COALESCE(O.discount, 0) / 100) |
| | 68 | |
| | 69 | - T ← γorder_num, client_id, client_name, quantity, |
| | 70 | status, payment_method, discount; |
| | 71 | Σ(P.price × quantity) |
| | 72 | × (1 - COALESCE(discount, 0) / 100) |
| | 73 | → order_total(J4) |
| | 74 | |
| | 75 | **Sort by order total:** |
| | 76 | - R_final ← τorder_total DESC(T) |
| | 77 | |
| | 78 | |