I am trying to get the oldest record for every status update/change in the following table.
Table (status_updates) :
id | entity_id | status | date |
---|---|---|---|
7 | 2 | Approved | 2022-02-10 |
6 | 2 | Approved | 2022-02-05 |
5 | 2 | Approved | 2022-02-04 |
4 | 2 | OnHold | 2022-02-04 |
3 | 2 | OnHold | 2022-02-03 |
2 | 2 | Approved | 2022-02-02 |
1 | 2 | Approved | 2022-02-01 |
Result Needed :
id | entity_id | status | date |
---|---|---|---|
5 | 2 | Approved | 2022-02-04 |
3 | 2 | OnHold | 2022-02-03 |
1 | 2 | Approved | 2022-02-01 |
Tried :
select
`status`,
`created_at`
from
`status_updates`
left join
(select
`id`,
row_number() over (partition by status_updates.entity_id, status_updates.status order by status_updates.created_at asc) as sequence
from
`status_updates`)
as `oldest_history`
on
`oldest_history`.`id` = `shipper_credit_histories`.`id`
where `sequence` = 1
Result Achived :
id | entity_id | status | date |
---|---|---|---|
3 | 2 | OnHold | 2022-02-03 |
1 | 2 | Approved | 2022-02-01 |
3
Answers
here are the queries:
or this query(if you prefer left join)
in both you will see the expected result
the second solution is almost the same, but join by id instead of date
result is the same what you expected
Just using lag: