I have the following 2 tables:
Process table
| PROCESS_ID | PROCESS_NAME |
| ------------ | ------------ |
| A_0001 | A1 |
| A_0002 | A2 |
| A_0003 | A3 |
Phase Tracking Table
PHASE_ID | PROCESS_ID | PHASE_NAME | DATE |
---|---|---|---|
1 | A_0001 | Draft | 10/01/2023 |
2 | A_0001 | Review | 13/01/2023 |
3 | A_0001 | Investigation | 15/01/2023 |
4 | A_0001 | Review | 18/01/2023 |
5 | A_0002 | Draft | 10/01/2023 |
6 | A_0002 | Review | 13/01/2023 |
7 | A_0002 | Draft | 15/01/2023 |
8 | A_0003 | Draft | 10/01/2023 |
9 | A_0003 | Review | 11/01/2023 |
Then, what I need to obtain is the latest phase for each process but with the min date for that phase in case the phase is not unique. For the data of the two previous tables, I would like to obtain the following result:
PROCESS_ID | PROCESS_NAME | PHASE_NAME | INITIAL DATE |
---|---|---|---|
A_0001 | A1 | Review | 13/01/2023 |
A_0002 | A2 | Draft | 10/01/2023 |
A_0003 | A3 | Review | 11/01/2023 |
As you can see, for process_id = A_0001
, the last phase is Review, but as we have a previous Review phase, we need to obtain the date for that phase, so 13/01/2023
instead of 18/01/2023
I've tried several queries already with HAVING
and GROUP PY
clauses.
4条答案
按热度按时间mzillmmw1#
Here's a straightforward way of thinking about the problem. You'll need to know which phase is the current state. Once that's determined it's easy to filter for all rows with that same state and then group to get the minimum date:
t9aqgxwy2#
Here is an option using with window functions
min() over()
androw_number()
in concert with aWITH TIES
Example or dbFiddle
Results
xtfmy6hx3#
eeq64g8w4#
first step i find PHASE_NAME and find min date per PHASE_NAME