在多个条件下获取最小值

jogvjijk  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(323)

我正在处理一个贷款数据集,我有以下代码来查找前30天、60天和90天的拖欠( dpdXX_mob )对于给定的交易密钥。脚本按预期工作,但我想知道是否有更有效的方法来获取这些值。

SELECT 
    90dpd.trade_key AS trade_key,
    90dpd.first_dpd90_mob,
    60dpd.first_dpd60_mob,
    30dpd.first_dpd30_mob
FROM (
        SELECT trade_key, min(mob) AS first_dpd90_mob
        FROM base_table
        WHERE 90_day_counter = 1
    ) AS 90dpd
    LEFT JOIN (
            SELECT trade_key, min(mob) AS first_dpd60_mob
            FROM base_table
            WHERE 60_day_counter = 1
        ) AS 60dpd
          ON 90dpd.trade_key = 60dpd.trade_key
    LEFT JOIN (
            SELECT trade_key, min(mob) AS first_dpd30_mob
            FROM base_table
            WHERE 30_day_counter = 1
        ) AS 30dpd
          ON 90dpd.trade_key = 30dpd.trade_key
zbwhf8kr

zbwhf8kr1#

使用条件聚合:

select trade_key,  
       min(case when 90_day_counter = 1 then mob end) first_dpd90_mob,
       min(case when 60_day_counter = 1 then mob end) first_dpd60_mob,
       min(case when 30_day_counter = 1 then mob end) first_dpd30_mob
from base_table
group by trade_key

相关问题