STRING_AGG
函数应该能够实现这一点.
每个Value_New
应由' -> '
分隔,并应按Changed_Date
字段排序.AGROUP BY
将需要包括在内.
select ac."id_Parent_Record"
,ac."Field_Changed"
, STRING_AGG(ac."Value_New", ' -> ' ORDER BY ac."Changed_Date" asc) AS "Transitions"
from public.api_changelog ac
where ac."Field_Changed" IN ('_id_Matter','Task_Workflow')
and ac."id_Parent_Record" = '637454609993200'
GROUP BY ac."id_Parent_Record"
,ac."Field_Changed"
;
输出:
id_Parent_Record |
Field_Changed |
Transitions |
637454609993200 |
_id_Matter |
637417579791350 |
637454609993200 |
Task_Workflow |
Initial Referral -> IRU -> Adjustment Approved -> Settlement |
可以使用CTE将表重新联接回原始结果集
WITH transitions AS (
select ac."id_Parent_Record"
,ac."Field_Changed"
, STRING_AGG(ac."Value_New", ' -> ' ORDER BY ac."Changed_Date" asc) AS "Transitions"
from public.api_changelog ac
where ac."Field_Changed" IN ('_id_Matter','Task_Workflow')
and ac."id_Parent_Record" = '637454609993200'
GROUP BY ac."id_Parent_Record"
,ac."Field_Changed"
)
select ac."id_Parent_Record"
,ac."Field_Changed"
,ac."Value_Previous"
,ac."Value_New"
,ac."Changed_Date"
, t."Transitions"
from public.api_changelog ac
INNER JOIN transitions t
ON ac."id_Parent_Record" = t."id_Parent_Record"
AND ac."Field_Changed" = t."Field_Changed"
;
id_Parent_Record |
Field_Changed |
Value_Previous |
Value_New |
Changed_Date |
Transitions |
637454609993200 |
_id_Matter |
|
637417579791350 |
2021-01-07 |
637417579791350 |
637454609993200 |
Task_Workflow |
|
Initial Referral |
2021-01-05 |
Initial Referral -> IRU -> Adjustment Approved -> Settlement |
637454609993200 |
Task_Workflow |
Initial Referral |
IRU |
2021-01-06 |
Initial Referral -> IRU -> Adjustment Approved -> Settlement |
637454609993200 |
Task_Workflow |
IRU |
Adjustment Approved |
2021-03-26 |
Initial Referral -> IRU -> Adjustment Approved -> Settlement |
637454609993200 |
Task_Workflow |
Adjustment Approved |
Settlement |
2021-06-02 |
Initial Referral -> IRU -> Adjustment Approved -> Settlement |