| | 1 | = Approximate number of orders per client |
| | 2 | {{{#!sql |
| | 3 | CREATE OR REPLACE FUNCTION get_approximate_orders_per_client() |
| | 4 | RETURNS TABLE ( |
| | 5 | total_clients BIGINT, |
| | 6 | total_orders BIGINT, |
| | 7 | approximate_orders_per_client NUMERIC |
| | 8 | ) |
| | 9 | LANGUAGE plpgsql |
| | 10 | AS $$ |
| | 11 | BEGIN |
| | 12 | RETURN QUERY |
| | 13 | SELECT |
| | 14 | (SELECT COUNT(*) FROM client) AS total_clients, |
| | 15 | (SELECT COUNT(*) FROM "order") AS total_orders, |
| | 16 | ROUND( |
| | 17 | (SELECT COUNT(*) FROM "order")::NUMERIC |
| | 18 | / NULLIF((SELECT COUNT(*) FROM client), 0), |
| | 19 | 2 |
| | 20 | ) AS approximate_orders_per_client; |
| | 21 | END; |
| | 22 | $$; |
| | 23 | |
| | 24 | }}} |
| | 25 | |
| | 26 | == Relational Algebra |
| | 27 | - O(order_num, quantity, status, last_modified_date, payment_method, discount) |
| | 28 | - C(client_id, name, first_name, last_name, email, password, delivery_address) |
| | 29 | |
| | 30 | **Calculate total number of orders:** |
| | 31 | - O_total ← γCOUNT(order_num) → total_orders(O) |
| | 32 | |
| | 33 | **Calculate total number of clients:** |
| | 34 | - C_total ← γCOUNT(client_id) → total_clients(C) |
| | 35 | |
| | 36 | **Calculate approximate number of orders per client:** |
| | 37 | - R ← γclient_id, name; |
| | 38 | R ← πtotal_clients, |
| | 39 | total_orders, |
| | 40 | total_orders / total_clients |
| | 41 | → approximate_orders_per_client |
| | 42 | (C_total × O_total) |
| | 43 | |
| | 44 | |