[英]SQL comparing two date columns and keep the first row where 2nd column is larger
我有一個包含兩個日期列next_start_date
和cancel_date
。
group_id | 個人 ID | 取消日期 | 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 | 個人 ID | 取消日期 | next_start_date_after_cancel | days_customer_came_back |
---|---|---|---|---|
1 | 001 | 2017-11-06 | 2018-04-16 | 161 |
2 | 001 | 2018-06-04 | 無效的 | 無效的 |
2 | 001 | 2018-08-28 | 無效的 | 無效的 |
這個想法是我想比較兩列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
請幫忙...
使用FILTER
排除大於next_start_date_after_cancel
的cancel_date
,在子查詢或 CTE 中獲取它的min()
值。 最后減去兩個日期以獲得不同的天數:
WITH j AS (
SELECT
group_id,individual_id,cancel_date,
min(next_start_date_after_cancel) FILTER (WHERE next_start_date_after_cancel > cancel_date) AS next_start_date_after_cancel
FROM t GROUP BY 1,2,3)
SELECT
group_id,individual_id,cancel_date,next_start_date_after_cancel,
next_start_date_after_cancel-cancel_date
FROM j;
演示: db<>fiddle
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.