【问题标题】:presto split single column value to multiple rowspresto 将单列值拆分为多行
【发布时间】:2021-01-24 18:08:21
【问题描述】:

我在 presto 上有一个包含多条记录的表。从那条记录中,我使用了这个简单的 SQL 查询,

select id, data from my_table where id IN (1,7)

这是我从那个查询中得到的,

id        data
1   ('A', 0.0, 12)
7   ('B', 0.0, 20) ('A', 0.0, 30) ('C', 0.0, 40)

现在我想将这个数据列设置为多行,如下所示,基本上,将单列值拆分为多行。

name value age
A    0.0   12
B    0.0   20
A    0.0   30
C    0.0   40

到目前为止我已经尝试过,但在 presto 上出现错误

SELECT data
FROM my_table
    CROSS APPLY STRING_SPLIT(data, ' ') where id IN (1,7); 

我的想法是用空格分割列值,然后用逗号再次分割以在最后形成多列。似乎我需要使用来自heresplit()split_part(),但我无法让它工作。请告诉我该怎么做?

【问题讨论】:

标签: sql join presto amazon-athena


【解决方案1】:

使用splitunnestreplacetry 我现在可以执行查询只是想知道有没有其他方法可以解决/修复它?因为我对这种方式并不完全满意:)

WITH t AS (
select data  from my_table where id IN (1,7)
)

SELECT
  try(trim(data_parts[1])) AS name,
  try(trim(data_parts[2])) AS age,
  try(trim(data_parts[3])) AS value
FROM (
  SELECT split(replace(split_Col2,'('),',') as data_parts 
FROM t
CROSS JOIN UNNEST(SPLIT(data,')')) AS t (split_Col2) 
) WHERE length(try(trim(data_parts[1]))) > 0

结果

     name   age  value
34  'AAAA'  0.0 'NNNNN' 
36  'BBBB'  0.0 'NNNNN'     
38  'CCCC'  0.0 'MMMMM'
39  'AAAA'  0.0 'CCCCC'

【讨论】:

    猜你喜欢
    • 2021-11-04
    • 1970-01-01
    • 2011-07-04
    • 1970-01-01
    • 2011-07-05
    • 2020-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多