Using Postgres:
My AGREEMENT_T lists records that belong to a particular agreement_group_id. At any time, within a Group, either 1 is ACTIVE=Y, or 0 (at most 1).
ID AGREEMENT_GROUP_ID ACTIVE FIELD1 FIELD2 STATUS_ACTION_DATE
------------------------------------------------------------------
1 55 N 45 50 01-Oct-2021 00:03:05
2 55 Y 78 70 30-Sep-2021 03:04:05
3 100 N 44 4 02-Oct-2021 04:00:01
4 101 N 1 2 02-Oct-2021 04:01:05
5 101 N 0 1 05-Oct-2021 11:13:54
6 102 Y 3 3 05-Oct-2021 11:47:45
7 102 N 4 4 05-Oct-2021 11:48:49
I need to get a result that lists Agreement Group ID paired with
- If
ACTIVE=Yis available within a Group, then that Agreement ID - Else, the ID with the latest
STATUS_ACTION_DATEfor that Group
ex.
55 2
100 3
101 5
102 6
So far, I can pull up the latest STATUS_ACTION_DATE using Postgres' array_agg(..)[1] as follows,
SELECT agreement_group_id, (array_agg(id ORDER BY status_action_date DESC))[1] AS val
FROM ets.agreement_t
GROUP BY agreement_group_id
ORDER BY agreement_group_id
But is there a quick way to integrate that with finding ACTIVE=Y, maybe without using an extra SELECT EXISTS? Also something that performs well.