获取红移中的第N个非空列

时间:2018-03-15 23:10:12

标签: sql amazon-redshift

我有一个包含可空列的集合的表。我需要做的是转移'这些列"左"以便第1列包含第一个非空值,第2列包含第二个非空值,等等。

e.g。

This:

<null>, <null>, foo,    bar,    baz,    buz
<null>, <null>, <null>, <null>, foo,    bar
<null>, <null>, <null>, foo,    bar,    baz

需要成为这个:

foo,    bar,    baz,    buz,    <null>, <null>
foo,    bar,    <null>, <null>, <null>, <null>
foo,    bar,    baz,    <null>, <null>, <null>

我可以确定数据包含0个或更多列,后跟1个或多个非空列。

我可以想象一种通过无偿使用CASE陈述来实现这一目标的方法,但我宁愿不制造这样的憎恶。

任何人都知道如何轻松完成这项工作?

1 个答案:

答案 0 :(得分:1)

我认为最简单的方法是一个非透视/枢轴。你可以这样做:

select id,
       max(case when seqnum = 1 then col end) as col1,
       max(case when seqnum = 2 then col end) as col2,
       max(case when seqnum = 3 then col end) as col3,
       max(case when seqnum = 4 then col end) as col4,
       max(case when seqnum = 5 then col end) as col5,
       max(case when seqnum = 6 then col end) as col6
from (select t.*, row_number() over (partition by id order by pos) as seqnum
      from ((select id, col1 as col, 1 as pos from t) union all
            (select id, col2 as col, 2 as pos from t) union all
            (select id, col3 as col, 3 as pos from t) union all
            (select id, col4 as col, 4 as pos from t) union all
            (select id, col5 as col, 5 as pos from t) union all
            (select id, col6 as col, 6 as pos from t) 
           ) t
      where col is not null
     ) t
group by id;

因为Redshift是一个柱状数据库,所以union all应该与其他任何非数据删除方式一样高效。