如何从这个 table 中只获取 CH_PAY_MODE loan_id?

How to fetch only CH_PAY_MODE loan_id from this table?

loan_id coll_date coll_pay_mode
8007571771 APR-2022 CH
8007571771 FEB-2022 CH
8007571771 JAN-2022 CH
8007571771 MAR-2022 CH
8007571771 MAR-2022 CL
8007571771 MAY-2022 CH
8007636540 APR-2022 CH
8007636540 JAN-2022 CH
8007636540 MAR-2022 CH
8007636540 MAY-2022 CH

对于上面的数据,table 中给出了两个 loan_id,每月使用 CHCL 收集,所以我想获取 loan_id CL 任何一个月都没有付款。

实现所需结果的方法之一是使用 EXISTS 子句 -

SELECT DISTINCT loan_id
  FROM YOUR_TABLE T1
 WHERE coll_pay_mode = 'CH'
  AND NOT EXISTS (SELECT NULL
                    FROM YOUR_TABLE T2
                   WHERE T1.loan_id = t2.loan_id
                     AND T2.coll_pay_mode = 'CL')

使用条件聚合和 HAVING 子句的一个选项,例如

SELECT loan_id
  FROM t
 GROUP BY loan_id
HAVING SUM(CASE WHEN coll_pay_mode = 'CL' THEN 1 ELSE 0 END) = 0   

您也可以使用 LEFT JOIN 实现此目的:

SELECT distinct loan_id
FROM yourtable t1
LEFT JOIN yourtable t2
ON loan_id = t2.loan_id and
   t2.col1_pay_mode = 'CL'
WHERE t1.col1_pay_mode = 'CH' AND
      t2.col1_pay_mode IS NULL;

所以,我们做一个自我 left-join 来确保没有 t2t1 匹配,col1_pay_mode 是 CL,我们 select distinct 个值。