I have two tables:
tbl_status:
id
status_code
month_digest_id
project_id
tbl_project
id
name
tbl_month_digest:
id
month_ts
I have a project. Each project has a status for zero or more months (stored in tbl_month_digest). Given a list of project IDs I need to get the latest status object.
I am having trouble doing this. In MySQL I was be able to select from a join of tbl_month_digest and tbl_status and adding a having tbl_month_digest.month_ts = max(tbl_month_digest.month_ts). Postgres insists that I add tbl_month_digest.month_ts to a group by, which does not have the desired effect.
Is it possible to get the most recent status for a list of projects in a single SQL query in postgresql?
Example data and expected result:
tbl_month_digest:
id month_ts
1 2014-05-01
2 2014-06-01
3 2014-07-01
tbl_project:
id name
90 'Foundation'
91 'Testing'
92 'Examination'
tbl_status:
id project_id month_digest_id status_code
1 90 1 'on_track'
2 90 2 'on_track'
3 90 3 'late'
4 91 1 'late'
5 91 2 'unknown'
6 91 3 'unknown'
7 92 1 'late'
8 92 2 'late'
9 92 3 'on_track'
Given project IDs 90 and 91, I would like to get
project_id latest_status
90 'late'
92 'on_track'