从字符串数组中,创建一个表

时间:2015-01-15 22:45:04

标签: sql postgresql amazon-redshift

基本上,当给出一个字符串列表时,

我想创建一个包含select语句的表。

例如,

"A", "B", "C",

我想创建一个表作为子选择,如:

sub-select
+---------+
|   "A"   |
+---------+
|   "B"   |
+---------+
|   "C"   |
+---------+

如何在redshift和postgres中执行此操作?

谢谢!

更新

选择' a'作为A;

是我想要的东西:

     a
+---------+
|   "a"   |
+---------+

如何从查询a

为此列select 'a' as A;设置多行

3 个答案:

答案 0 :(得分:0)

没有机会在db中测试它,但类似的东西

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

答案 1 :(得分:0)

您可以使用string_to_arrayunnest

select *
from unnest(string_to_array('"A","B","C"', ','))

(但我不知道Redshift中是否提供此功能)

答案 2 :(得分:0)

将列值转换为多行的方法之一是使用split_part函数和UNION。

这是一个例子。

来源表:

=> 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)