I am trying to write a SQL query in MySQL Workbench that will return to me the sums of records I moved to a particular status considering only the latest timestamp for a particular record. I also need to do this without a sub query (or nested select).
Given the below table, I want to know that user with id 1 moved two records to status with id 2. I need to not include in my counts if the same record was moved to two different status ids, but only count the latest status id.
Table
user_id | acted_on_record_id | moved_to_status_id | timestamp |
---|---|---|---|
1 | 1234 | 2 | 2022-01-01 19:39:37 |
1 | 1234 | 3 | 2022-01-02 19:39:37 |
1 | 1234 | 2 | 2022-01-03 19:39:37 |
1 | 5678 | 2 | 2022-01-03 19:39:37 |
Here is the query I have so far:
SELECT t1.user_id, t1.acted_on_record_id,
SUM(DISTINCT IF(t1.moved_to_status_id = 3, 1, 0)) AS pending,
SUM(DISTINCT IF(t1.moved_to_status_id = 2, 1, 0)) AS open,
MAX(t1.timestamp) as timestamp
FROM table1 t1
GROUP BY t1.user_id, t1.acted_on_record_id
This is the result I want:
user_id | acted_on_record_id | pending | open | timestamp |
---|---|---|---|---|
1 | 1234 | 0 | 1 | 2022-01-03 19:39:37 |
1 | 5678 | 0 | 1 | 2022-01-03 19:39:37 |
However, my query gives me this result:
user_id | acted_on_record_id | pending | open | timestamp |
---|---|---|---|---|
1 | 1234 | 1 | 1 | 2022-01-03 19:39:37 |
1 | 5678 | 0 | 1 | 2022-01-03 19:39:37 |
It shows a 1 in both pending and 1 in open columns because the SUM IF aggregates are not mutually exclusive or distinct on the acted_on_record_id. Is there a way to have these two aggregates know about each other and only sum the one with the greater timestamp without using a sub query (nested select)?