0

我是 SQL json 功能
的新手,问题是:我想使用 SQL-JSON 功能从下表数据生成所需的 JSON 结构。

我拥有的标签数据:

Col1    | Col2   |  Col3  | Col4
--------------------------------
School  | Room   | Jon    | Present
School  | Room   | Hanna  |Absent
School  | Room   | Teena  | NA
School  | Hall   | Length | 12
School  | Hall   | Breath | 11
School  | Hall   | Heught | 4
School  | Ground | school | xuz
School  | Ground | col    | oo
School  | Ground | else   | a
College | ClassA | teacher| 2
College | ClassA | students|20
College | ClassA | others | 1
College | ClassB | Des    | 3
College | ClassB | tv     | 0

所需的 JSON 数据格式

{
    "School":{
    
        "Room":{
          "Jon":"Present",
          "Hanna":"Absent",
          "Teena":"NA"
        },
        "Hall":{
          "Length":"12",
          "Breath":"11",
          "Heught":"4"
        },
        "Ground":{
          "school":"xuz",
          "col":"oo",
          "else":"a"
        }   
        
    },
    "College":{
        "ClassA":{
          "teacher":"2",
          "students":"20",
          "others":"1"
        },
        "ClassB":{
          "Desk":"3",
          "tv":"0"
        }
    }
}

我需要知道如何在上述给定所需的 json 格式的帮助下格式化数据FOR JSON PATH

4

1 回答 1

0

使用 Postgres,您可以使用它jsonb_object_agg()来实现:

select jsonb_build_object(col1, jsonb_object_agg(col2, j1))
from (
  select col1, col2, jsonb_object_agg(col3, col4) as j1
  from t
  group by col1, col2
) t
group by col1;

在线示例

于 2020-07-23T19:32:55.517 回答