行类型的聚合列

aggregate column of type row

我想过滤一列rowtype,聚合rowtype,当它们有补充信息时。 所以我的数据看起来像这样:

|col1|rowcol                          |
|----|--------------------------------|
|1   |{col1=2, col2=null, col3=4}     |
|1   |{col1=null, col2=3, col3=null}  |
|2   |{col1=7, col2=8, col3=null}     |
|2   |{col1=null, col2=null, col3=56} |
|3   |{col1=1, col2=3, col3=7}        |

下面是一些代码,您可以使用它来创建一个工作示例:


    select col1, cast(rowcol as row(col1 integer, col2 integer, col3 integer))
    from (
    values 
        (1, row(2,null,4)),
        (1, row(null,3,null)),
        (2, row(7,8,null)),
        (2, row(null,null,56)),
        (3, row(1,3,7)) 
        ) 
    AS x (col1, rowcol)


我期待如下结果:

|col1|rowcol                         |
|----|-------------------------------|
|1   |{col1=2, col2=3, col3=4}       |
|2   |{col1=7, col2=8, col3=56}      |
|3   |{col1=1, col2=3, col3=7}       |

也许有人可以帮助我...

提前致谢

您需要按 col1 对它们进行分组并处理以合并非空值,例如使用 max:

-- sample data
WITH dataset (col1, rowcol) AS (
    VALUES  
        (1, row(2,null,4)),
        (1, row(null,3,null)),
        (2, row(7,8,null)),
        (2, row(null,null,56)),
        (3, row(1,3,7)) 
) 

--query
select col1,
    cast(row(max(r.col1), max(r.col2), max(r.col3)) as row(col1 integer, col2 integer, col3 integer)) rowcol
from (
        select col1,
            cast(rowcol as row(col1 integer, col2 integer, col3 integer)) r
        from dataset
    )
group by col1
order by col1 -- for ordered output

输出:

col1 rowcol
1 {col1=2, col2=3, col3=4}
2 {col1=7, col2=8, col3=56}
3 {col1=1, col2=3, col3=7}