sql - 优雅地总结 AWS Athena 中的多个列,不包括空值
问题描述
我必须通过在 AWS Athena 中添加一些其他列来创建total_costs
、total_proceeds
和列。total_net_loss
我还必须替换nulls
为zeros
,否则结果将为空。我尝试使用sum()
函数,但它仅适用于单列。以下查询完成了我想做的事情,但看起来很不优雅。有没有其他更优雅的方式来总结列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;
解决方案
使用SUM
和COALESCE
组合,像这样:
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)
推荐阅读
- c - MATLAB/Simulink - C MEX S-Function:总线信号和涉及指针的传统 C 结构之间的转换
- sql - 如何在 SQL 中使用 SQL 条件语句
- docker - Last Docker Desktop for Windows 安装崩溃
- r - 在 R 中将 %H:%M:%S 添加为 as.POSIXct 格式
- android - Android在使用谷歌日历api时给IOException“无法创建目录:/tokens”
- r - 在 R 中的数据框的每个元素上应用带有参数的函数
- throw - 我不是程序员:“throw”是指特定的代码元素还是像“show”这样的通用术语?
- csv - # 在 CSV 标题中
- java - Spring boot - MongoRepository 日期转换
- laravel-nova - Laravel Nova - 如何确定资源计算字段的视图(索引、详细信息、表单)?