Hive 查询派生列并找到派生列的总数

Hive query for derived columns and find the total of derived column

我有一个场景,其中 credit_Date、debit_date 和 loan_date 可以相同。输出 table 有以下列

日期:应结合 credit_date、debit_date 和 loan_date(credit_date、debit_date 和 loan_date 可以相同(或)空)

Credit_payment: 计算给定 credit_date、实体、货币、所有者

的信用额度总和

Debit_payment: 计算给定 debit_date、实体、货币、所有者

的借方金额总和

Loan_payment: 求给定 loan_date、实体、货币、所有者

的贷款总额

实体: 来自 Table1

的值

货币: 值来自 Table 1

所有者: 值来自 Table 1

总计: (credit_payment + debit_payement+ loan_payment)

的总和

我试过下面的查询但没有用

insert into table2 
select *
from (
    select credit_date as date, sum(credit_amount) as credit_payment, null as debit_payment, null as loan_payment, entity, owner, currency
    from table1
    group by credit_date, entity, owner, currency
    union all
    select debit_date as date, null as credit_payment, sum(debit_amount) as debit_payment, null as loan_payment, entity, owner, currency
    from table1
    group by debit_date, entity,owner, currency 
    union all
    select loan_date as date, null as credit_payment, null as debit_payment, sum(loan_amount) as loan_payment, entity, owner, currency
    from table1
    group by loan_date, entity, owner, currency
) t
order by date;

您可以使用coalesce将group by前的三个日期组合起来。它将处理空值。

select coalesce(credit_date, debit_date, loan_date) as date, 
       sum(credit_amount) as credit_payment, 
       sum(debit_amount) as debit_payment,
       sum(loan_amount) as loan_payment,
       entity, currency, owner,
       sum(credit_amount) + sum(debit_amount) + sum(loan_amount) as Total
from table1
group by coalesce(credit_date, debit_date, loan_date), entity, currency, owner