gpt4 book ai didi

sql - 在 postgres 中嵌套加入聚合

转载 作者:行者123 更新时间:2023-11-29 12:23:24 25 4
gpt4 key购买 nike

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

  1. 事件类型
    • ID(主键)
    • 姓名
  2. 事件类型
    • ID(主键)
    • 姓名
    • 事件类型 ID(外键)
    • 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
}
]
}
]

最佳答案

您可以像下面描述的那样加入自己的表作为父表。

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"

关于sql - 在 postgres 中嵌套加入聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56784825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com