| | 1 | = Employees ordered by total hours worked and total pay |
| | 2 | {{{#!sql |
| | 3 | CREATE OR REPLACE FUNCTION get_employees_by_hours_and_pay() |
| | 4 | RETURNS TABLE ( |
| | 5 | ssn BIGINT, |
| | 6 | employee_name TEXT, |
| | 7 | total_hours_worked NUMERIC, |
| | 8 | total_pay NUMERIC |
| | 9 | ) |
| | 10 | LANGUAGE plpgsql |
| | 11 | AS $$ |
| | 12 | BEGIN |
| | 13 | RETURN QUERY |
| | 14 | SELECT |
| | 15 | e.ssn, |
| | 16 | p.name AS employee_name, |
| | 17 | COALESCE(SUM(w.working_hours), 0) AS total_hours_worked, |
| | 18 | COALESCE(SUM(w.wage), 0) AS total_pay |
| | 19 | FROM employees e |
| | 20 | JOIN personal p |
| | 21 | ON e.ssn = p.ssn |
| | 22 | LEFT JOIN worked w |
| | 23 | ON e.ssn = w.ssn |
| | 24 | GROUP BY |
| | 25 | e.ssn, |
| | 26 | p.name |
| | 27 | ORDER BY |
| | 28 | total_hours_worked DESC, |
| | 29 | total_pay DESC; |
| | 30 | END; |
| | 31 | $$; |
| | 32 | |
| | 33 | }}} |
| | 34 | |
| | 35 | == Relational Algebra |
| | 36 | - E(employee_id, date_of_hire) |
| | 37 | - P(id, name, first_name, last_name, email, password, permissions, type, authorisation) |
| | 38 | - W(id, date, store_ID, week, total_week, pay_method, wage, working_hours) |
| | 39 | |
| | 40 | **JOIN employees with personal information:** |
| | 41 | - J1 ← E ⨝E.employee_id = P.idP |
| | 42 | |
| | 43 | **JOIN employees with work records:** |
| | 44 | - J2 ← J1 ⟕E.employee_id= W.id W |
| | 45 | |
| | 46 | **Calculate total hours and pay for each employee:** |
| | 47 | - total_hours_worked = Σ(working_hours) |
| | 48 | - total_pay = Σ(wage) |
| | 49 | - R ← γSSN, name; |
| | 50 | Σ(working_hours) → total_hours_worked, |
| | 51 | Σ(wage) → total_pay |
| | 52 | (J2) |
| | 53 | |
| | 54 | **Sort by total hours worked and total pay:** |
| | 55 | - R_final ← τtotal_hours_worked DESC, |
| | 56 | total_pay DESC(R) |
| | 57 | |
| | 58 | |