| | 1 | = Top 10 employees who have answered the most amount of request in the last month |
| | 2 | {{{#!sql |
| | 3 | CREATE OR REPLACE FUNCTION get_top_10_employees_by_requests_last_month() |
| | 4 | RETURNS TABLE ( |
| | 5 | ssn BIGINT, |
| | 6 | employee_name TEXT, |
| | 7 | number_of_requests BIGINT |
| | 8 | ) |
| | 9 | LANGUAGE plpgsql |
| | 10 | AS $$ |
| | 11 | BEGIN |
| | 12 | RETURN QUERY |
| | 13 | SELECT |
| | 14 | e.ssn, |
| | 15 | p.name AS employee_name, |
| | 16 | COUNT(DISTINCT a.request_num) AS number_of_requests |
| | 17 | FROM employees e |
| | 18 | JOIN personal p |
| | 19 | ON e.ssn = p.ssn |
| | 20 | JOIN answers a |
| | 21 | ON e.ssn = a.ssn |
| | 22 | JOIN request r |
| | 23 | ON a.request_num = r.request_num |
| | 24 | WHERE r.date_and_time >= date_trunc('month', CURRENT_DATE) - INTERVAL '1 month' |
| | 25 | AND r.date_and_time < date_trunc('month', CURRENT_DATE) |
| | 26 | GROUP BY |
| | 27 | e.ssn, |
| | 28 | p.name |
| | 29 | ORDER BY |
| | 30 | number_of_requests DESC |
| | 31 | LIMIT 10; |
| | 32 | END; |
| | 33 | $$; |
| | 34 | |
| | 35 | }}} |
| | 36 | |
| | 37 | == Relational Algebra |
| | 38 | - E(employee_id, date_of_hire) |
| | 39 | - P(id, name, first_name, last_name, email, password, permissions, type, authorisation) |
| | 40 | - A(request_num, id) |
| | 41 | - R(request_num, date_and_time, problem, notes_of_communication, customer_satisfaction) |
| | 42 | |
| | 43 | **JOIN employees with their personal information:** |
| | 44 | - J1 ← E ⨝E.empployee_id = P.id P |
| | 45 | - J2 ← J1 ⨝E.emplyee_id = A.id A |
| | 46 | |
| | 47 | **JOIN employees with corresponding requests:** |
| | 48 | - J3 ← J2 ⨝A.request_num = R.request_num R |
| | 49 | |
| | 50 | **SELECT requests completed from the last calendar month:** |
| | 51 | - F1 ← σ |
| | 52 | date_and_time ≥ START_OF_CURRENT_MONTH - 1 MONTH |
| | 53 | ∧ |
| | 54 | date_and_time < START_OF_CURRENT_MONTH |
| | 55 | (J3) |
| | 56 | |
| | 57 | **Calculate total number of distinct requests each employee has answered:** |
| | 58 | - R1 ← γSSN, name; |
| | 59 | COUNT(DISTINCT request_num) → number_of_requests |
| | 60 | (F1) |
| | 61 | |
| | 62 | **Sort by number of requests answered:** |
| | 63 | - R2 ← τnumber_of_requests DESC(R1) |
| | 64 | |
| | 65 | **Return only TOP 10 employees:** |
| | 66 | - R_final ← LIMIT 10(R2) |
| | 67 | |
| | 68 | |