【问题标题】:Get rows with a condition获取有条件的行
【发布时间】:2021-03-01 22:22:03
【问题描述】:

每个客户可以拥有一个或多个帐户 (account_id)

我怎样才能为关闭所有帐户的客户和其余活跃客户获得最大closed_date?*

*活跃客户是至少有一个开户的客户。

+-------------+------------+--------------+-------------+
| 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/10/2020  |
| 12kju       | gege1      | 07/03/2020   | 01/07/2020  |
| 12kju       | mhfl1      | 08/03/2020   | 03/07/2020  |
+-------------+------------+--------------+-------------+

期望的输出:

+-------------+-------------+
| customer_id | closed_date |
+-------------+-------------+
| 3eba3       |             |
| 5hlf1       |             |
| hdk12       | 01/10/2020  |
| 12kju       | 03/07/2020  |
+-------------+-------------+ 

【问题讨论】:

    标签: sql postgresql datetime where-clause greatest-n-per-group


    【解决方案1】:

    您可以为此使用distinct on

    select distinct on (customer_id) t.*
    from t
    order by customer_id, closed_date desc nulls first;
    

    根据order by 子句,每个customer_id 返回一行。

    【讨论】:

    • 不错的方法。一些建议:在查询中使用 t.* 是一种低效的做法(对于较小的数据库:psql、mysql)。
    【解决方案2】:

    您可以使用聚合和case 表达式:

    select customer_id,
        case when bool_and(closed_date is not null) then max(closed_date) end as closed_date
    from mytable
    group by customer_id
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-11
      • 2012-12-17
      • 1970-01-01
      相关资源
      最近更新 更多