在 postgres 中嵌套加入聚合

Nested Join with aggregation in posgres

在我的数据库中,有两个表

  1. 事件类型
    • ID(主键)
    • 姓名
  2. 活动类型
    • ID(主键)
    • 姓名
    • EventTypeID(外键)
    • ParentActivityTypeID(与自己 ID 的关系)

我尝试使用以下查询来聚合 json

SELECT  coalesce(json_build_object(
        'EventTypeID', ev."ID",
        'EventTypeName', ev."Name",
        'ActivityType', json_agg(json_build_object('ID',ac."ID",'Name',ac."Name",'ParentActivityType',json_agg(select * from "Activity" where ))
    ), '{}'::json)  AS item
FROM  "EventType" as ev
JOIN  "ActivityType" as ac ON ev."ID" = ac."EventTypeID"
GROUP  BY ev."ID"

预期JSON输出

[{
  "EventTypeID": 2,
  "EventTypeName": "On-Site Care",
  "ActivityType": [
    {
      "ID": 1,
      "Name": "Measurement",
      "EventTypeID": 2,
      "ParentActivityTypeID": null,
      "SubActivityType": [
        {
          "ID": 17,
          "Name": "abc",
          "EventTypeID": 2,
          "ParentActivityTypeID": 1
        }
      ]
    },
    {
      "ID": 2,
      "Name": "Medication",
      "EventTypeID": 2,
      "ParentActivityTypeID": null
    },
    {
      "ID": 3,
      "Name": "Wellness check",
      "EventTypeID": 2,
      "ParentActivityTypeID": null
    },
    {
      "ID": 4,
      "Name": "Other",
      "EventTypeID": 2,
      "ParentActivityTypeID": null
    }
  ]
},
{
  "EventTypeID": 3,
  "EventTypeName": "Care Call",
  "ActivityType": [
    {
      "ID": 1,
      "Name": "Measurement",
      "EventTypeID": 3,
      "ParentActivityTypeID": null,
      "SubActivityType": [
        {
          "ID": 17,
          "Name": "abc",
          "EventTypeID": 3,
          "ParentActivityTypeID": 1
        }
      ]
    },
    {
      "ID": 2,
      "Name": "Medication",
      "EventTypeID": 3,
      "ParentActivityTypeID": null
    },
    {
      "ID": 3,
      "Name": "Wellness check",
      "EventTypeID": 3,
      "ParentActivityTypeID": null
    },
    {
      "ID": 4,
      "Name": "Other",
      "EventTypeID": 3,
      "ParentActivityTypeID": null
    }
  ]
}
]

您可以加​​入自己 table 作为家长,如下所述。

SELECT  coalesce(json_build_object(
        'EventTypeID', ev."ID",
        'EventTypeName', ev."Name",
        'ActivityType', json_agg(json_build_object('ID',ac."ID",'Name',ac."Name",'ParentActivityType',json_agg(parent.*))
    ), '{}'::json)  AS item
FROM  "EventType" as ev
LEFT JOIN  "EventType" as parent ON ev."ParentActivityTypeID" = parent."ID"
JOIN  "ActivityType" as ac ON ev."ID" = ac."EventTypeID"
GROUP  BY ev."ID"