我有以下表数据..表名是类别
| ID | Data |
+----------------+--------------------------+
| 1 | Apple,Orance-........... |
| 2 | Apple,Grapes-........... |
| 3 | Juice,Apple,Cucumber-... |
有没有办法可以将上面的逗号分隔值转换为个别行的值,如下所示?
| ID | SplitData
+-------------+-------------------
| 1 | Apple
| 2 | Orange
| 3 | Grapes
| 4 | Juice
| 5 | Cucumber
我使用postgres for db和Jersey来检索数据,
答案 0 :(得分:1)
在string_to_array()
中使用unnest()
:
with a_table(id, data) as (
values
(1, 'Apple,Orance'),
(2, 'Apple,Grapes'),
(3, 'Juice,Apple,Cucumber')
)
select id, elem
from a_table,
lateral unnest(string_to_array(data, ',')) elem
id | elem
----+----------
1 | Apple
1 | Orance
2 | Apple
2 | Grapes
3 | Juice
3 | Apple
3 | Cucumber
(7 rows)
使用distinct
获取不同的元素:
with a_table(id, data) as (
values
(1, 'Apple,Orance'),
(2, 'Apple,Grapes'),
(3, 'Juice,Apple,Cucumber')
)
select distinct on (elem) elem
from a_table,
lateral unnest(string_to_array(data, ',')) elem
elem
----------
Apple
Cucumber
Grapes
Juice
Orance
(5 rows)