![](/img/trans.png)
[英]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.