简体   繁体   中英

Combine multiple rows into single row with JSON object as columns

I have a table which I'm trying to reduce the dataset by combing all ID/Section combinations into a single row (where there are 3 total sections) with nested JSON. The table schema looks like:

| ID       | Section  | Country  | Date   |
| -------- | -------- | -------- | ------ |
| 1        | 1        | US       | 1-1-11 |
| 1        | 2        | US       | 1-1-11 |
| 1        | 3        | US       | 1-1-11 |
| 1        | 1        | CA       | 1-1-11 |
| 1        | 2        | CA       | 1-1-11 |
| 1        | 3        | CA       | 2-2-22 |
| 1        | 1        | MX       | 2-2-22 |
| 1        | 2        | MX       | 2-2-22 |
| 1        | 3        | MX       | 2-2-22 |
| 2        | 1        | US       | 3-3-33 |

I would like to perform a query to transform this to something that combines id/section and the country and dates into a JSON string

| ID/Section | Country/dates                      |
| ---------- | ---------------------------------- |
| "1,1"      | {"US;CA":”1-1-11;","MX":"2-2-22;"} |
| "1,2"      | {"US;CA":”1-1-11;","MX":"2-2-22;"} |
| "1,3"      | {"US":”1-1-11;","CA;MX":"2-2-22;"} |
| "2,1"      | {"US":”3-3-33;"}                   |

You need two group by for that and concat needed columns.

First we group by id, section, date, after only by id and section.

select id || ',' || section as id_section, '{'|| listagg(temp, ',') || '}' as country_dates
from (select id, section, '"' || listagg(country, ';') || '"' || ':' || '"' || date || '"' as temp
      from test.temp
      group by id, section, date) as t1
group by id, section;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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