| | 1 | = Products ordered by number of orders from highest to lowest |
| | 2 | {{{#!sql |
| | 3 | CREATE OR REPLACE FUNCTION get_products_by_number_of_orders() |
| | 4 | RETURNS TABLE ( |
| | 5 | product_code INT, |
| | 6 | product_description TEXT, |
| | 7 | product_price NUMERIC, |
| | 8 | number_of_orders BIGINT |
| | 9 | ) |
| | 10 | LANGUAGE plpgsql |
| | 11 | AS $$ |
| | 12 | BEGIN |
| | 13 | RETURN QUERY |
| | 14 | SELECT |
| | 15 | p.code AS product_code, |
| | 16 | p.description AS product_description, |
| | 17 | p.price AS product_price, |
| | 18 | COUNT(DISTINCT o.order_num) AS number_of_orders |
| | 19 | FROM product p |
| | 20 | JOIN includes i |
| | 21 | ON p.code = i.code |
| | 22 | JOIN "order" o |
| | 23 | ON i.order_num = o.order_num |
| | 24 | GROUP BY |
| | 25 | p.code, |
| | 26 | p.description, |
| | 27 | p.price |
| | 28 | ORDER BY |
| | 29 | number_of_orders DESC; |
| | 30 | END; |
| | 31 | $$; |
| | 32 | |
| | 33 | }}} |
| | 34 | |
| | 35 | == Relational Algebra |
| | 36 | - P(code, price, availability, description, ...) |
| | 37 | - O(order_num, quantity, status, last_modified_date, payment_method, discount) |
| | 38 | - I(code, order_num) |
| | 39 | |
| | 40 | **JOIN products with orders:** |
| | 41 | - J1 ← P ⟕P.code = I.code I |
| | 42 | - J2 ← J1 ⟕I.order_num = O.order_num O |
| | 43 | |
| | 44 | **Calculate the number of distinct orders the product has been in:** |
| | 45 | - R ← γcode, description, price; |
| | 46 | COUNT(DISTINCT order_num) → number_of_orders |
| | 47 | (J2) |
| | 48 | |
| | 49 | **Sort by total orders:** |
| | 50 | - R_final ← τnumber_of_orders DESC(R) |
| | 51 | |
| | 52 | |