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 | 0 |
1 | 1 |
1 | 2 |
1 | 3 |
1 | 4 |
1 | 5 |
1 | 6 |
1 | 7 |
2 | 0 |
2 | 1 |
2 | 2 |
2 | 3 |
2 | 4 |
2 | 5 |
2 | 6 |
2 | 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. I tried 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:
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)
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.