获取具有条件的行
Get rows with a condition
每个客户可以拥有一个或多个帐户(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 |
+-------------+-------------+
您可以为此使用 distinct on
:
select distinct on (customer_id) t.*
from t
order by customer_id, closed_date desc nulls first;
这 returns 每 customer_id
一行基于 order by
子句。
您可以使用聚合和 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
每个客户可以拥有一个或多个帐户(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 |
+-------------+-------------+
您可以为此使用 distinct on
:
select distinct on (customer_id) t.*
from t
order by customer_id, closed_date desc nulls first;
这 returns 每 customer_id
一行基于 order by
子句。
您可以使用聚合和 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