3 回答

TA貢獻(xiàn)1843條經(jīng)驗(yàn) 獲得超7個(gè)贊
如果CSV中的字段數(shù)是常數(shù),那么您可以執(zhí)行以下操作:
select a[1], a[2], a[3], a[4]
from (
select regexp_split_to_array('a,b,c,d', ',')
) as dt(a)
例如:
=> select a[1], a[2], a[3], a[4] from (select regexp_split_to_array('a,b,c,d', ',')) as dt(a);
a | a | a | a
---+---+---+---
a | b | c | d
(1 row)
如果CSV中的字段數(shù)不是常數(shù),那么您可以使用以下內(nèi)容獲得最大字段數(shù):
select max(array_length(regexp_split_to_array(csv, ','), 1))
from your_table
然后a[1], a[2], ..., a[M]為您的查詢(xún)構(gòu)建適當(dāng)?shù)牧辛斜?。因此,如果上面給出的最大值為6,那么你可以使用:
select a[1], a[2], a[3], a[4], a[5], a[6]
from (
select regexp_split_to_array(csv, ',')
from your_table
) as dt(a)
如果需要,可以將這兩個(gè)查詢(xún)組合成一個(gè)函數(shù)。
例如,提供此數(shù)據(jù)(在最后一行中為NULL):
=> select * from csvs;
csv
-------------
1,2,3
1,2,3,4
1,2,3,4,5,6
(4 rows)
=> select max(array_length(regexp_split_to_array(csv, ','), 1)) from csvs;
max
-----
6
(1 row)
=> select a[1], a[2], a[3], a[4], a[5], a[6] from (select regexp_split_to_array(csv, ',') from csvs) as dt(a);
a | a | a | a | a | a
---+---+---+---+---+---
1 | 2 | 3 | | |
1 | 2 | 3 | 4 | |
1 | 2 | 3 | 4 | 5 | 6
| | | | |
(4 rows)
由于您的分隔符是一個(gè)簡(jiǎn)單的固定字符串,您也可以使用string_to_array而不是regexp_split_to_array:
select ...
from (
select string_to_array(csv, ',')
from csvs
) as dt(a);
感謝Michael提供有關(guān)此功能的提醒。
您真的應(yīng)該重新設(shè)計(jì)數(shù)據(jù)庫(kù)架構(gòu),以便盡可能避免使用CSV列。您應(yīng)該使用數(shù)組列或單獨(dú)的表。

TA貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超13個(gè)贊
split_part() 一步完成你想做的事:
SELECT split_part(col, ',', 1) AS col1
, split_part(col, ',', 2) AS col2
, split_part(col, ',', 3) AS col3
, split_part(col, ',', 4) AS col4
FROM tbl;
添加盡可能多的項(xiàng)目col(可能的最大值)。超出數(shù)據(jù)項(xiàng)的列將為空字符串('')。

TA貢獻(xiàn)1809條經(jīng)驗(yàn) 獲得超8個(gè)贊
您可以使用拆分功能。
SELECT (select top 1 item from dbo.Split(FullName,',') where id=1 ) Column1, (select top 1 item from dbo.Split(FullName,',') where id=2 ) Column2, (select top 1 item from dbo.Split(FullName,',') where id=3 ) Column3, (select top 1 item from dbo.Split(FullName,',') where id=4 ) Column4, FROM MyTbl
添加回答
舉報(bào)