在红移中填充表为0

时间:2017-05-16 20:57:17

标签: sql amazon-redshift

我有一张表格:

id |  A | B |  C
 -----------------
 1 |  1 | 0 |  1
 1 |  2 | 1 |  0
 2 |  1 | 4 |  0

我想用0s(不包括id)填充此表,这样每个id都有3个条目。结果将是:

id |  A | B |  C
 -----------------
 1 |  0 | 0 |  0
 1 |  1 | 0 |  1
 1 |  2 | 1 |  0
 2 |  0 | 0 |  0
 2 |  0 | 0 |  0
 2 |  1 | 4 |  0

这是因为id 1有两个条目,所以我们添加了一行0,而id 2有一个条目,所以我们添加了两行0。

注意:我们可以假设每个id出现的次数不超过3次,并且如果id恰好出现3次,则无需添加填充。

使用Amazon Redshift有一种智能的方法吗?我需要将其缩放到30天的填充和几百列。

1 个答案:

答案 0 :(得分:3)

如果A列始终是连续的,您可以执行以下操作:

select i.id, n.num,
       coalesce(t.b, 0) as b,
       coalesce(t.c, 0) as c
from (select distinct id from t) i cross join
     (select 1 as num union all select 2 union all select 3) n left join
     t on i.id = t.id and n.num = t.A;

您需要列出select中的每一列以获取零。

如果上述情况不属实,您可以使用CTE确认:

with t as (
      select t.*, row_number() over (partition by id order by id) as num
      from t
     )
select i.id, coalesce(t.a, 0) as a,
       coalesce(t.b, 0) as b,
       coalesce(t.c, 0) as c
from (select distinct id from t) i cross join
     (select 1 as num union all select 2 union all select 3) n left join 
     t on i.id = t.id and n.num = t.num;