【问题标题】:Format complex json structure on grouped data with sql server使用 sql server 在分组数据上格式化复杂的 json 结构
【发布时间】:2020-07-23 18:47:25
【问题描述】:

我是 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"
        }
    }
}

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

【问题讨论】:

  • 你用的是postgres还是sql server?您的问题被标记为两者。
  • 我使用的是sql server
  • 我认为您不能仅使用 FOR JSON 生成此 JSON 输出。

标签: sql sql-server sql-server-2016 sql-server-2017 for-json


【解决方案1】:

使用 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;

Online example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-09
    • 2020-08-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多