【发布时间】:2021-07-09 03:14:47
【问题描述】:
我有一个包含两个日期列 next_start_date 和 cancel_date 的表格。
| group_id | individual_id | cancel_date | next_start_date_after_cancel |
|---|---|---|---|
| 1 | 001 | 2017-11-06 | 2014-03-26 |
| 1 | 001 | 2017-11-06 | 2017-01-09 |
| 1 | 001 | 2017-11-06 | 2018-04-16 |
| 2 | 001 | 2018-06-04 | 2014-03-26 |
| 2 | 001 | 2018-06-04 | 2017-01-09 |
| 2 | 001 | 2018-06-04 | 2018-04-16 |
| 2 | 001 | 2018-08-28 | 2014-03-26 |
| 2 | 001 | 2018-08-28 | 2017-01-09 |
| 2 | 001 | 2018-08-28 | 2018-04-16 |
所需输出:days_customer_came_back 是计算列:
| group_id | individual_id | cancel_date | next_start_date_after_cancel | days_customer_came_back |
|---|---|---|---|---|
| 1 | 001 | 2017-11-06 | 2018-04-16 | 161 |
| 2 | 001 | 2018-06-04 | null | null |
| 2 | 001 | 2018-08-28 | null | null |
我的想法是我想比较cancel_date 和next_start_date_after_cancel 这两列,next_start_date_after_cancel 必须在cancel_date 之后才能获得这些日期之间的正日差。
如果对于同一个cancel_date 有多个“next_start_date_after_cancel”,我们只保留第一个最小值,而忽略其他的。
另外,对于cancel_date的条目,如果所有可用的next_start_date_after_cancel都在cancel_date之前,我们会将其替换为null,并将日差输出为null
请帮忙...
【问题讨论】:
标签: python sql postgresql