Tessella's analytics team receives timesheet extracts with inconsistent formatting, duplicate updates, missing references, and mixed approval states. Write a PostgreSQL query that converts the raw extract into a monthly analysis-ready table.
Requirements
- Keep only the latest record for each
timesheet_id, based on updated_at.
- Parse the date and decimal hours, normalize billable flags, and retain approved rows with hours from 0 through 24.
- Use left joins to retain approved entries even when the consultant or project reference is missing. Label missing references as
Unknown consultant or Unknown project.
- Aggregate by month, consultant, and project, returning total, billable, non-billable hours, and entry count. Sort chronologically, then by consultant and project.
Output details
- Return columns in this order:
month, consultant_name, project_code, project_name, total_hours, billable_hours, non_billable_hours, entry_count.
- Break
updated_at ties by descending ingestion_id.
- Parse
work_date_text as DD/MM/YYYY, replace decimal commas with periods, trim values, and treat blank hours as NULL.
- Treat trimmed, case-insensitive
yes, y, true, and 1 as billable; treat every other value as non-billable.
- Match approved status case-insensitively after trimming, and exclude rows whose parsed hours are
NULL.
- Sort ascending by
month, consultant_name, and project_code, using project_code to break consultant ties; preserve numeric precision without rounding.