使用 window 函数计算行数

Counting rows with a window function

每个客户可以拥有一个或多个帐户 (account_id)。 要找到客户流失,必须关闭与客户关联的所有帐户,即 closed_date

例如这里的客户流失率是 2。

如何让 Postgres 中的客户流失? 提前致谢!

+-------------+------------+--------------+-------------+
| customer_id | account_id | created_date | closed_date |
+-------------+------------+--------------+-------------+
| 3eba3       | 5dddd      | 17/06/2020   |             |
| 3eba3       | eabbd      | 29/06/2020   |             |
| 3eba3       | 9f3a4      | 29/06/2020   | 09/11/2020  |
| 5hlf1       | khti1      | 01/02/2020   |             |
| hdk12       | sfsf2      | 05/03/2020   | 01/06/2020  |
| hdk12       | sfsl3      | 06/03/2020   | 01/06/2020  |
| 12kju       | gege1      | 07/03/2020   | 01/07/2020  |
| 12kju       | mhfl1      | 08/03/2020   | 03/07/2020  |
+-------------+------------+--------------+-------------+

您可以使用聚合:

select count(*)
from (
    select customer_id
    from mytable
    group by customer_id
    having bool_and(closed_date is not null)
) t

另一种选择是 count(distinct)not exists:

select count(distinct customer_id)
from mytable t
where not exists (
    select 1 
    from mytable t1 
    where t1.customer_id = t.customer_id and t1.closed_date is null
)

如果你只是想要计数,你可以使用聚合:

select (count(distinct customer_id) -
        count(distinct customer_id) filter (where closed_date is not null)
       )
from accounts;

这会计算数据中的客户数量,然后减去拥有未结账户的客户数量。