使用现有列创建新列,但在非排他性条件下

问题描述 投票:0回答:1

这是一个案例研究。

我有下表,T1 有两列:c1,c2

    C1     C2
    1       3
    5       2
    4       10

我想创建一个表 T2,同时包含 C1、C2 和一个新列 C3,其定义方式是

 if C1 > 3  then C3 = "C1_big"
 if C2 > 3  then C3 = "C2_big"
 else C3 = "not_big"

所以使用我们的表T1,我们得到

    C1     C2     C3
    1       3     "not_big"
    5       2     "C1_big"
    4       10    "C1_big"
    4       10    "C2_big"

注意最后一行同时满足“C1_big”和“C2_big”的条件,所以我们有两行。

我正在考虑使用 CASE WHEN,但它只适用于相互排斥的事件。对于我们的案例,“C1_big”、“C2_big”都可以连续发生,因此不需要相互排斥。

有没有办法在 SQL 查询中实现这一点?任何帮助将不胜感激。

sql schema partition group
1个回答
1
投票

在 Presto/Trino 中,这可以使用 array functions

unnest
(这里使用简洁的语法)来实现:

-- sample data
with dataset (c1, c2) as (
    values (1, 3),
        (5, 2),
        (4, 10)
)

-- query
select *
from dataset,
     unnest(
        if(
             c1 <= 3 and c2 <=3, array['not_big'],
             filter(array[if(c1 > 3, 'C1_big'), if(c2 > 3, 'C2_big')], x -> x is not null)
        )) as t(c3);

不使用 Presto 特定的功能 - 你可以使用

union all
:

-- query
select *, 'not_big' c3
from dataset
where c1 <= 3
  and c2 <= 3

union all

select *, 'C1_big' c3
from dataset
where c1 > 3

union all

select *, 'C2_big' c3
from dataset
where c2 > 3;
© www.soinside.com 2019 - 2024. All rights reserved.