根据其他列值回填值

时间:2018-06-29 04:11:03

标签: sql stored-procedures greenplum

我有什么

customerid   status_1 status_2 status_3 status_4 status_5

Ax             1         0         0        0        0
Bx             0         0         1        0        0
Cx             0         0         0        0        1
Dx             0         0         0        1        0
Ex             0         1         0        0        0

我想根据其他列值回填列中的值

  1. 如果status_1 = 1,则status_2,status_3,status_4和status_5应该为0。

  2. 如果status_2 = 1,则status_1应该为1,status_3,status_4和status_5应该为0。

  3. 如果status_3 = 1,则status_1和status 2应该为1,status_4和status_5应该为0。

  4. 如果status_4 = 1,则status_1,status 2和status 5应该为1,status_3应该为0。

  5. 如果status_5 = 1,则status_1,status_2,status_3和status_4应该为1。

输出如下所示

 customerid   status_1 status_2 status_3 status_4 status_5

Ax         1         0         0        0        0
Bx         1         1         1        0        0
Cx         1         1         1        1        1
Dx         1         1         0        1        1
Ex         1         1         0        0        0

2 个答案:

答案 0 :(得分:0)

尝试一下:

select customer_id,
    case when status_5 = 1 or status_4 = 1 or status_3 = 1 or status_2 = 1 or status_1 = 1 then 1 else 0 end as status_1,
    case when status_5 = 1 or status_4 = 1 or status_3 = 1 or status_2 = 1 then 1 else 0 end as status_2,
    case when status_5 = 1 or status_3 = 1 then 1 else 0 end as status_3,
    case when status_5 = 1 or status_4 = 1 then 1 else 0 end as status_4,
    case when status_5 = 1 or status_4 = 1 then 1 else 0 end as status_5
from your_table;

答案 1 :(得分:0)

下面是 BACKFILL 查询将产生所需的结果。

此外,在添加新列ex.status6,status7,status8,...之后,以下查询所需的更改也较少。

当列需要 EXCEPTIONS (例如status_4

)时,会添加select中的“添加”和“或”

由于您的情况下status_1始终为1,因此您可以用1代替(1 <= pos.one)

    with your_table(customerid,status_1,status_2,status_3,status_4,status_5) as (
    select *
    from (
      values
        ('AX',1,0,0,0,0),
        ('BX',0,0,1,0,0),
        ('CX',0,0,0,0,1),
        ('DX',0,0,0,1,0),
        ('EX',0,1,0,0,0)
     ) t
    )
    select
     customerid,
     (1<=pos.one)::int as status1,
     (2<=pos.one)::int as status2,
     (3<=pos.one and pos.one!=4)::int as status3,
     (4<=pos.one)::int as status4,
     (5<=pos.one or pos.one=4)::int as status5
    from
    your_table t,
    lateral
    (
     select position('1' in t.status_1::text||t.status_2||t.status_3||t.status_4||t.status_5) as one
    ) pos