简体   繁体   English

SQL使用分组和聚合行到Json数组

[英]SQL Rows to Json Array with grouping and aggregation

My goal is to take data from a row with a specific ID and convert it into a JSON object to insert into another table. 我的目标是从具有特定ID的行中获取数据,并将其转换为JSON对象以插入到另一个表中。 What I'm starting with looks like this 我刚开始的是这样的

      Event_Details
-----------------------------------
ID | ID2  | First_Name| Last_Name | 
-----------------------------------
1X | 2B   | John      | Smith     |
2X | 2B   | Adam      | John      | 
3X | 2B   | Sarah     | Jones     | 
1X | 5C   | Joe       | Rob       |

What I want looks like this: 我想要的是这样的:

[
  {
    "id2": "2B",
    "event": {
      "ID": "1X",
      "First_Name": "John",
      "Last_Name": "Smith" 
    }
  },
{
    "id2": "5C",
    "event": {
      "ID": "1X",
      "First_Name": "Joe",
      "Last_Name": "Rob" 
    }
  }
]

I need to group the items into a single JSON object by "ID" but I want the id2 outside of the "Event" array. 我需要通过“ID”将项目分组到单个JSON对象中,但我希望id2在“Event”数组之外。

This is what I have so far which does the first thing, I'm just having trouble nesting the query for the array inside of it: 这是我到目前为止做的第一件事,我只是在为它内部的数组嵌套查询时遇到了麻烦:

select json_agg (b)
        from (select ID2 as "ID2"
        from event_details 
)b

I believe this is what you are looking for: 我相信这就是你要找的东西:

select json_agg(jsonb_build_object('id2', id2, 
                    'event', jsonb_build_object('ID', id, 
                                                 'First_Name', first_name, 
                                                 'Last_Name', last_name
))) 
from event_details group by id;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM