[英]How to compare the current row with next and previous row in PostgreSQL?
[英]How to compare current row with previous column next row in sql
Date from Date to
2018-12-11 2019-01-08
2019-01-08 2019-02-09
2019-02-10 2019-03-14
2019-03-17 2019-04-11
2019-04-15 2019-05-16
2019-05-16 2019-06-13
輸出將是這樣的
Date from Date to Days
2018-12-11 2019-01-08 0
2019-01-08 2019-02-09 1
2019-02-10 2019-03-14 3
2019-03-17 2019-04-11 4
2019-04-15 2019-05-16 0
2019-05-16 2019-06-13 -
你想要lead()
和一個日期差異函數:
select
date_from,
date_to,
datediff(day, date_to, lead(date_from) over(order by date_from)) days
from mytable
datediff()
是一個 SQLServer 函數。 在其他 RDBMS 中也有等價物。
旁注:對於沒有下一條記錄的記錄,我建議再次使用字符串值 ( -
),因為其他值是數字(列中的數據類型必須一致)。 null
就足夠了(上面的查詢將產生)。
date_from | date_to | days :------------------ | :------------------ | ---: 11/12/2018 00:00:00 | 08/01/2019 00:00:00 | 0 08/01/2019 00:00:00 | 09/02/2019 00:00:00 | 1 10/02/2019 00:00:00 | 14/03/2019 00:00:00 | 3 17/03/2019 00:00:00 | 11/04/2019 00:00:00 | 4 15/04/2019 00:00:00 | 16/05/2019 00:00:00 | 0 16/05/2019 00:00:00 | 13/06/2019 00:00:00 | null
要以天為單位返回兩個日期值之間的差異,您可以使用 DATEDIFF() 函數,例如:
SELECT DATEDIFF(DAY, DayFrom, DayTo) AS 'DaysBetween'
FROM DateTable
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.