在 SQL postgresql 中解析 key:value 对
parse key:value pairs in SQL postgresql
我有一个字符串,其中包含以分号分隔的键值对列表。
例如ref:12345;code:ab等
我想将其拆分为 'ab' 作为代码,'241376' 作为参考等
非常感谢任何帮助。
您可以使用 regexp_split_to_table 和 split_part 的组合。
CREATE TABLE t (myText text);
INSERT INTO t VALUES ('ref:12345;code:ab;ref:5678;code:cd');
SELECT
split_part(pair, ':', 1) as name,
split_part(pair, ':', 2) as value
FROM
(SELECT regexp_split_to_table(myText, ';') pair FROM t) t1
结果:
name
value
ref
12345
code
ab
ref
5678
code
cd
db<>fiddle here
更新
根据您的评论,如果您想要的结果是:
xxx 作为代码
xxx 作为参考
您可以使用:
SELECT
CONCAT(split_part(pair, ':', 2), ' as ', split_part(pair, ':', 1)) RESULT
FROM (SELECT regexp_split_to_table(myText, ';') pair FROM t) t1
那个returns:
result
12345 as ref
ab as code
5678 as ref
cd as code
db<>fiddle here
有点乱,但我希望不言自明。
with t as
(
select (r + 1)/2 as r,
split_part(txt, ':', 1) as k,
split_part(txt, ':', 2) as v
from unnest(string_to_array('ref:12345;code:ab;ref:5678;code:cd;ref:9876;code:yz', ';'))
with ordinality as t(txt, r)
)
select
max(v) filter (where k = 'ref') as ref_fld,
max(v) filter (where k = 'code') as code_fld
from t group by r;
结果:
ref_fld
code_fld
12345
ab
9876
yz
5678
cd
我有一个字符串,其中包含以分号分隔的键值对列表。
例如ref:12345;code:ab等
我想将其拆分为 'ab' 作为代码,'241376' 作为参考等
非常感谢任何帮助。
您可以使用 regexp_split_to_table 和 split_part 的组合。
CREATE TABLE t (myText text);
INSERT INTO t VALUES ('ref:12345;code:ab;ref:5678;code:cd');
SELECT
split_part(pair, ':', 1) as name,
split_part(pair, ':', 2) as value
FROM
(SELECT regexp_split_to_table(myText, ';') pair FROM t) t1
结果:
name | value |
---|---|
ref | 12345 |
code | ab |
ref | 5678 |
code | cd |
db<>fiddle here
更新
根据您的评论,如果您想要的结果是:
xxx 作为代码
xxx 作为参考
您可以使用:
SELECT
CONCAT(split_part(pair, ':', 2), ' as ', split_part(pair, ':', 1)) RESULT
FROM (SELECT regexp_split_to_table(myText, ';') pair FROM t) t1
那个returns:
result |
---|
12345 as ref |
ab as code |
5678 as ref |
cd as code |
db<>fiddle here
有点乱,但我希望不言自明。
with t as
(
select (r + 1)/2 as r,
split_part(txt, ':', 1) as k,
split_part(txt, ':', 2) as v
from unnest(string_to_array('ref:12345;code:ab;ref:5678;code:cd;ref:9876;code:yz', ';'))
with ordinality as t(txt, r)
)
select
max(v) filter (where k = 'ref') as ref_fld,
max(v) filter (where k = 'code') as code_fld
from t group by r;
结果:
ref_fld | code_fld |
---|---|
12345 | ab |
9876 | yz |
5678 | cd |