查找从未满足条件的行

时间:2021-06-18 23:06:53

标签: sql

假设我有一张客户表,其中包含三种可能的状态:贷款违约、未结贷款、全额付款。

如何找到从未违约的客户?

示例:John 和 Alex 有多项不同状态的贷款。

id | customer | status
----------------------
1     john     default
1     john     open
1     john     paid
2     alex     open
2     alex     paid

约翰违约一次,亚历克斯从未违约。简单的 where status <> "default" 尝试不起作用,因为它错误地包含了 John 的非默认情况。结果应该给我:

id | customer
-------------
2     alex

3 个答案:

答案 0 :(得分:3)

<块引用>

如何找到从未违约的客户?

您可以使用聚合和having

select id, customer
from t
group by id, customer
having sum(case when status = 'default' then 1 else 0 end) = 0;

having 子句计算每个客户的违约数量,并返回没有违约的客户。

如果您有单独的客户表,我建议not exists

select c.*
from customers c
where not exists (select 1
                  from t
                  where t.id  = c.id and t.status = 'default'
                 );

答案 1 :(得分:1)

类似的东西

select distinct `customer` from `customers` 
    where `customer` not in (
        select `customer` from `customers where `status` = 'default'
    );

答案 2 :(得分:0)

带有相关子查询的 ALL() 运算符在这里工作:

WITH cte AS (
    SELECT * FROM (VALUES
        (1, 'john', 'default'),
        (1, 'john', 'open'),
        (1, 'john', 'paid'),
        (2, 'alex', 'open'),
        (2, 'alex', 'paid')
    ) AS x(id, customer, status)
)
SELECT *
FROM cte AS a
WHERE 'default' <> ALL (
    SELECT status
    FROM cte AS b
    WHERE a.id = b.id
);

如果您只需要用户和/或 ID,请使用 select distinct «your desired columns» 而不是 select *