【问题标题】:How to use SQL to flatten a table with arrays in multiple columns?如何使用 SQL 将包含多列数组的表展平?
【发布时间】:2018-12-27 02:33:16
【问题描述】:

如何使用 num 和 letter 列中的数组转换此表:

 id  |    num    |  letter
-----+-----------+-----------
 111 | [1, 2]    | [a, b]
 111 | [3, 4]    | [c, d]
 222 | [5, 6, 7] | [e, f, g]

进入这张表

 id  | num | letter
-----+-----+--------
 111 |   1 | a
 111 |   2 | b
 111 |   3 | c
 111 |   4 | d
 222 |   5 | e
 222 |   6 | f
 222 |   7 | g

附录: 这里有一些 sql 可以尝试执行转换

with test as(
  select * from (
    values
        (111, array[1,2], array['a','b']),
        (111, array[3,4], array['c','d']),
        (222, array[5,6,7], array['e','f', 'g'])
  ) as t (id, num, letter)
)
select
 *
from test

【问题讨论】:

    标签: sql arrays presto


    【解决方案1】:

    PrestoDB 似乎支持带有多个参数的unnest()

    select t.id, u.n, u.l
    from test cross join
         unnest(num, letter) as u(n, l)
    

    【讨论】:

    • 谢谢,效果很好!我是每个列的单独交叉连接,但这当然行不通!
    • @RexSalisbury 您可以在取消嵌套之前将数组压缩在一起:prestodb.io/docs/current/functions/array.html#zip
    • @DainSundstrom 很好奇你是否有一个例子来说明它的样子。还有什么优势吗?
    猜你喜欢
    • 2015-03-19
    • 2016-11-29
    • 1970-01-01
    • 2019-08-08
    • 2016-03-16
    • 2012-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多