简体   繁体   English

将文本字段/数组展平/取消嵌套到多个级别

[英]Flattening/unnesting a text field/array to multiple levels

I need to flatten a text column to two separate columns.我需要将一个文本列展平为两个单独的列。 I'm using:我正在使用:

SELECT s.CoolerShelf,
       s.ShelfPosition,
 FROM planogram
  CROSS JOIN LATERAL UNNEST(string_to_array(shelves, ','))
      WITH ORDINALITY s(CoolerShelf,ShelfPosition)

Result:结果:

[["8d2cf35d-5708-45e0-9cb6-acad358e0f92" 1
"5a91f7a2-029a-46d7-8440-9337dd1b87d3" 2
"521562a9-9d33-438d-8156-1e6b1874ec8e" 3
"e14817e4-6630-4dca-a188-ac71060dcac9" 4
"76967052-ba9d-43f5-afd4-b4bbe1452d7e" 5
"2e5a6fb2-071e-426b-ac55-69f16baa0b42" 6
"108f263d-ee78-4124-a94b-2c5641f90321" 7
"0dbe5016-9e78-4173-b6e6-ff3e0199ca2e"] 8
["9bd83b79-186d-4ae5-9373-956dbd515070" 9
"b6172191-fa44-436d-879d-c883e4d240ed" 10
"093b72ba-74cd-48b9-86df-7e7d9341ae53" 11
"88b6c7f8-1d23-4e82-b959-8cb3400cc039" 12
"8279d979-8a57-4595-b9d3-346f6b05924e" 13
"735e6139-0fce-4bb7-a4a2-00ceb86c9b07" 14
"0ad84c4f-e0d8-4606-b563-8b2e32cc632f" 15
"5a86f7ea-0763-4473-ba09-91398e938be7"]} 16

Desired result:期望的结果:

coolershelf冷藏架 shelfposition货架位置
1 1个 0 0
1 1个 1 1个
1 1个 2 2个
1 1个 3 3个
1 1个 4 4个
1 1个 5 5个
1 1个 6 6个
1 1个 7 7
2 2个 0 0
2 2个 1 1个
2 2个 2 2个
2 2个 3 3个
2 2个 4 4个
2 2个 5 5个
2 2个 6 6个
2 2个 7 7

The numbering needs to start from the beginning after every open and closed parenthesis and I'd like to replace guid values with actual numbers.编号需要在每个左括号和右括号之后从头开始,我想用实际数字替换 guid 值。 I tried UNENST(string_to_array) .我尝试UNENST(string_to_array)

Considering that your text column uses [ and ] to separate the groups of guid on two levels, we can convert the text into json format so that these characters are recognized as array start and end and then use the json_array_elements function to split the json arrays. Try this:考虑到您的文本列使用[]将 guid 的组分隔为两个级别,我们可以将文本转换为json格式,以便将这些字符识别为数组开始和结束,然后使用json_array_elements function 拆分 json arrays。尝试这个:

SELECT s.id AS CoolerShelf,
       (t.id - 1) AS ShelfPosition,
 FROM planogram
  CROSS JOIN LATERAL json_array_elements(shelves :: json)
      WITH ORDINALITY AS s(content,id)
 CROSS JOIN LATERAL json_array_elements(s.content)
      WITH ORDINALITY AS t(content,id)

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

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