简体   繁体   English

优雅地总结 AWS Athena 中的多个列,不包括空值

[英]Gracefully sum multiple columns in AWS Athena excluding nulls

I have to create total_costs , total_proceeds , and total_net_loss columns by adding few other columns in AWS Athena.我必须通过在 AWS Athena 中添加一些其他列来创建total_coststotal_proceedstotal_net_loss列。 I also have to replace nulls with zeros , otherwise the result will be null.我还必须用zeros替换nulls ,否则结果将为 null。 I tried to use sum() function but it works only on the single column.我尝试使用sum()函数,但它仅适用于单列。 The following query accomplishes what I want to do but looks very ungracefully.以下查询完成了我想做的事情,但看起来很不雅观。 Is there any other, more elegant way to sum columns in Athena ?有没有其他更优雅的方法来对Athena列求和?

SELECT loan_identifier,
       monthly_reporting_period,
       current_actual_upb, 
       current_loan_delinquency_status, 
       (COALESCE(foreclosure_costs,0) + COALESCE(property_preservation_and_repair_costs,0) + COALESCE(asset_recovery_costs,0) + COALESCE(miscellaneous_holding_expenses_and_credits,0) + COALESCE(associated_taxes_for_holding_property,0)) AS total_costs,
       (COALESCE(net_sale_proceeds,0) + COALESCE(credit_enhancement_proceeds,0) + COALESCE(repurchase_make_whole_proceeds,0) + COALESCE(other_foreclosure_proceeds,0)) AS total_proceeds,
       current_actual_upb + (current_actual_upb * ((current_interest_rate/100 - 0.0035)/12)*DATE_DIFF('day', last_paid_installement_date, disposition_date)/30) + (COALESCE(foreclosure_costs,0) + COALESCE(property_preservation_and_repair_costs,0) + COALESCE(asset_recovery_costs,0) + COALESCE(miscellaneous_holding_expenses_and_credits,0) + COALESCE(associated_taxes_for_holding_property,0)) - (COALESCE(net_sale_proceeds,0) + COALESCE(credit_enhancement_proceeds,0) + COALESCE(repurchase_make_whole_proceeds,0) + COALESCE(other_foreclosure_proceeds,0)) AS total_net_loss
FROM performance_data;

Use SUM and COALESCE in combination, like this:结合使用SUMCOALESCE ,如下所示:

SELECT SUM(COALESCE(y, 0) + COALESCE(z, 0)) AS aggregate_sum_of_y_and_z
FROM (
  VALUES (1, 2),
         (NULL, 3),
         (2, 1)) AS x (y, z)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM