从字符串数组创建一个 table
From a string array, create a table
基本上,当给定一个字符串列表时,
我想用 select
语句创建一个 table。
例如,
"A", "B", "C",
我想创建一个 table 作为子 select,例如:
sub-select
+---------+
| "A" |
+---------+
| "B" |
+---------+
| "C" |
+---------+
如何在 redshift 和 postgres 中执行此操作?
谢谢!
更新:
select 'a' as A;
是我想要的 returns:
a
+---------+
| "a" |
+---------+
如何从查询 select 'a' as A;
中为该列 a
设置多行
没有机会在数据库中测试它,但类似的东西
select * INTO table from (
SELECT CAST('A' AS VARCHAR(100)) AS col
UNION ALL
SELECT 'B' AS col
UNION ALL
SELECT 'C' AS col
) a
您可以使用 string_to_array
和 unnest
select *
from unnest(string_to_array('"A","B","C"', ','))
(但我不知道在 Redshift 中是否可用)
将列值转换为多行的方法之一是使用 split_part 函数和 UNION。
这是一个例子。
来源Table:
=> CREATE TABLE t_csv (value varchar(64));
=> INSERT INTO t_csv VALUES ('"A","B","C"');
=> INSERT INTO t_csv VALUES ('"D","E"');
=> INSERT INTO t_csv VALUES ('"F","G","H","I"');
=> SELECT * FROM t_csv;
value
-----------------
"D","E"
"A","B","C"
"F","G","H","I"
(3 rows)
这是获取多行的查询。
=> WITH a AS (SELECT value FROM t_csv)
SELECT * FROM
(
SELECT split_part(a.value,',',1) AS value FROM a
UNION
SELECT split_part(a.value,',',2) AS value FROM a
UNION
SELECT split_part(a.value,',',3) AS value FROM a
UNION
SELECT split_part(a.value,',',4) AS value FROM a
)
WHERE value != '';
value
-------
"A"
"B"
"C"
"D"
"E"
"F"
"G"
"H"
"I"
(9 rows)
基本上,当给定一个字符串列表时,
我想用 select
语句创建一个 table。
例如,
"A", "B", "C",
我想创建一个 table 作为子 select,例如:
sub-select
+---------+
| "A" |
+---------+
| "B" |
+---------+
| "C" |
+---------+
如何在 redshift 和 postgres 中执行此操作?
谢谢!
更新:
select 'a' as A;
是我想要的 returns:
a
+---------+
| "a" |
+---------+
如何从查询 select 'a' as A;
a
设置多行
没有机会在数据库中测试它,但类似的东西
select * INTO table from (
SELECT CAST('A' AS VARCHAR(100)) AS col
UNION ALL
SELECT 'B' AS col
UNION ALL
SELECT 'C' AS col
) a
您可以使用 string_to_array
和 unnest
select *
from unnest(string_to_array('"A","B","C"', ','))
(但我不知道在 Redshift 中是否可用)
将列值转换为多行的方法之一是使用 split_part 函数和 UNION。
这是一个例子。
来源Table:
=> CREATE TABLE t_csv (value varchar(64));
=> INSERT INTO t_csv VALUES ('"A","B","C"');
=> INSERT INTO t_csv VALUES ('"D","E"');
=> INSERT INTO t_csv VALUES ('"F","G","H","I"');
=> SELECT * FROM t_csv;
value
-----------------
"D","E"
"A","B","C"
"F","G","H","I"
(3 rows)
这是获取多行的查询。
=> WITH a AS (SELECT value FROM t_csv)
SELECT * FROM
(
SELECT split_part(a.value,',',1) AS value FROM a
UNION
SELECT split_part(a.value,',',2) AS value FROM a
UNION
SELECT split_part(a.value,',',3) AS value FROM a
UNION
SELECT split_part(a.value,',',4) AS value FROM a
)
WHERE value != '';
value
-------
"A"
"B"
"C"
"D"
"E"
"F"
"G"
"H"
"I"
(9 rows)