Impala 查询中的值相乘

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

我正在尝试将 Impala 中的值相乘。以下是我的声明,并附有结果输出的屏幕截图。该计算适用于某些行,而对于其他行则返回 NULL。

SELECT
 a.bom_number
,a.plant
,a.component_assembly_bom_material_number
,a.bom_component_material_number
,a.level
,a.Assembly_Flag
,a.level_1_inclusion
,a.level_2_inclusion
,a.level_3_inclusion
,a.level_4_inclusion
,a.level_5_inclusion
,a.level_6_inclusion
,a.level_7_inclusion
,a.level_8_inclusion
,a.level_9_inclusion
,a.level_10_inclusion
,coalesce(
a.level_1_inclusion * 
a.level_2_inclusion * 
a.level_4_inclusion * 
a.level_5_inclusion * 
a.level_6_inclusion *
a.level_7_inclusion *
a.level_8_inclusion *
a.level_9_inclusion *
a.level_10_inclusion ,1) Final
FROM tmp_levels a
[current output](https://i.stack.imgur.com/l5ryS.png)

output

所有行中的值都会正确相乘

sql math impala
1个回答
0
投票

使用一些虚拟数据:

create table #test
(
    one int,
    two int,
    three int,
    four int,
    five int
)

insert into #test values
(1, 2, 3, 4, 5),
(1, null, 2, 3, 4),
(1, 2, null, 3, null),
(null, null, null, null, null)

这说明了一些选项,具体取决于您想要如何处理缺失值(您的问题尚不清楚):

select
    one, two, three, four, five,
    one * two * three * four * five as rawOutput,
    coalesce(one * two * three * four * five, 1) as badCoalesce,
    isnull(one, 1) * isnull(two, 1) * isnull(three, 1) * isnull(four, 1) * isnull(five, 1) as betterCoalesce,
    case 
        when coalesce(one, two, three, four, five) is null 
        then null 
        else isnull(one, 1) * isnull(two, 1) * isnull(three, 1) * isnull(four, 1) * isnull(five, 1) 
    end as handleAllNull
from #test

结果:

一个 两个 原始输出 不良合并 更好的结合 处理AllNull
1 2 3 4 5 120 120 120 120
1 2 3 4 1 24 24
1 2 3 1 6 6
1 1
© www.soinside.com 2019 - 2024. All rights reserved.