sql - 在 Redshift 中拆分行

标签 sql postgresql amazon-redshift

在我的表格中,数据如下:

col1    col2    col3    col4
A1      A2      A3      4
B1      B2      B3      3   
C1      C2      C3      1

我需要如下输出:

col1    col2    col3    col4
A1      A2      A3      1
A1      A2      A3      2
A1      A2      A3      3
A1      A2      A3      4
B1      B2      B3      1   
B1      B2      B3      2   
B1      B2      B3      3   
C1      C2      C3      1

我正在使用 Redshift DB。

最佳答案

您是对的,Redshift 目前不支持generate_series。解决这个问题的一种方法是生成您自己的系列表并加入其中。在下面的示例中,我只是对 pg_attribute 表执行了 row_number() 来生成序列。您可以调整 TOP (v) 值来调整序列中您想要的许多数字,如果您需要的数字超出 pg_attribute 所能提供的数字,请尝试将 pg_attribute 与其自身交叉连接。我并不认为这是生成序列表的最佳方法,您可以以任何您想要的方式生成它;我的主要观点是,您需要一个来替代generate_series。

一旦有了系列表,就可以通过简单的连接来获得结果。 完整示例:

-- Setup Example
CREATE TABLE test
(
    col1 char(2),
    col2 char(2),
    col3 char(2),
    col4 integer
);

INSERT INTO test(col1, col2, col3, col4)
VALUES 
    ('A1', 'A2', 'A3', 4),
    ('B1', 'B2', 'B3', 3),
    ('C1', 'C2', 'C3', 1);


-- Generate 10 sequence numbers to table.  Adjust as needed or roll your own
SELECT TOP 10 ROW_NUMBER() OVER (PARTITION BY attnum ORDER BY attnum) n
INTO sequence
FROM pg_catalog.pg_attribute;

-- Example Query
SELECT col1, col2, col3, s.n
FROM test t
     INNER JOIN sequence s ON s.n <= t.col4
ORDER BY col1, col2, col3, s.n;

-- Clean up
DROP TABLE sequence;
DROP TABLE test;

关于sql - 在 Redshift 中拆分行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22779150/

相关文章:

mysql - 使用 count 函数时,什么会导致此查询提供此错误?

sql - ORACLE SQL,其中结尾需要时间

java - Apache Storm 一次性处理

sql - postgres 不断给出 "schema does not exist"错误

sql - 转置然后将表格导出到 CSV 文件

ruby-on-rails - 在 Rails 中查找具有多个外键值的记录

python - 使用装饰器通过 psycopg2 访问数据库

postgresql - 开拓者 + 身份 : why there is an error?

python - Redshift Python UDFs Varchar 限制

hadoop - 有没有办法将数据从redshift加载到HDFS?