将sql查询转换为嵌套的json

busg9geu  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(486)

我有以下sql查询:

SELECT att.prod_name, att.prod_group, att.prod_size, obj.physical_id, obj.variant, max(obj.last_updated_date)
FROM Table1 obj
join Table2 att
on obj.prod_name = att.prod_name
where
obj.access_state = 'cr' 
AND obj.variant in ('Front')
AND obj.size_code in ('LARGE')
AND att.prod_name in ('prod_1','prod_2')
group by 1,2,3,4,5

当前输出如下所示:

prod_name          prod_group       prod_size      physical_id    variant       max
prod_1              1              Large - 2 Oz   jnjnj3lnzhmui   Front      8/8/2020
prod_1              1              Large - 2 Oz   pokoknujyguin   Front      6/8/2020
prod_2              1              Large - 3 Oz   oijwu8ygtoiim   Front      4/2/2018
prod_2              1              Large - 3 Oz   ytfbeuxxxx2u2   Front      7/2/2018
prod_2              1              Large - 3 Oz   rtyferqdctyyx   Front      4/4/2020

如何将其转换为查询本身中的嵌套json?所需输出:(变量和最大日期可忽略)

{"prod_name":"prod_1" , "prod_group":"1", "prod_size":"Large - 2 Oz", "physical_id":{"physical_id_1":"jnjnj3lnzhmui", "physical_id2" : "pokoknujyguin"}}

{"prod_name":"prod_2" , "prod_group":"1", "prod_size":"Large - 3 Oz", "physical_id":{"physical_id_1":"oijwu8ygtoiim", "physical_id2" : "ytfbeuxxxx2u2", "physical_id3" : "rtyferqdctyyx"}}
7hiiyaii

7hiiyaii1#

如上所述,redshift没有像bigquery那样内置json语句 TO_JSON() 或sql server FOR JSON .
因此,您要么自己用java或python之类的编码语言编写转换,要么编写一堆字符串操作代码,直接在redshift中“伪造”。
类似于:

SELECT CHR(123) || '"prod_name"'|| ':' || '"' || nvl(prod_name,0) || '"' || ',' || 
'"prod_group"'|| ':' || '"' || nvl(prod_group,'') || '"' || ',' || 
'"prod_size"'|| ':' || '"' || nvl(prod_size,'') || '"' || Chr(125) FROM TABLE1

nvl保护您不受空值(如果存在)的影响。筑巢方面变得有点困难,但有足够的耐心,你应该达到那里。
祝你好运!

相关问题