2

In my DB, there are two tables

  1. EventType
    • ID (Primary key)
    • Name
  2. ActivityType
    • ID (Primary key)
    • Name
    • EventTypeID (foreign key)
    • ParentActivityTypeID (Relation with self ID)

I have tried with the following query to aggregate the 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"

expected JSON output

[{
  "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
    }
  ]
}
]

1 Answer 1

1

You can join self table as parent described as below.

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"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.