[英]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
output will be like this输出将是这样的
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 -
You want lead()
and a date diff function:你想要
lead()
和一个日期差异函数:
select
date_from,
date_to,
datediff(day, date_to, lead(date_from) over(order by date_from)) days
from mytable
datediff()
is a SQLServer function. datediff()
是一个 SQLServer 函数。 There are equivalents in other RDBMS.在其他 RDBMS 中也有等价物。
Side note: I would recommend againts using a string value ( -
) for records that do not have a next record, since other values are numeric (the datatypes in a column must be consistant).旁注:对于没有下一条记录的记录,我建议再次使用字符串值 (
-
),因为其他值是数字(列中的数据类型必须一致)。 null
is good enough for this (which the above query will produce). null
就足够了(上面的查询将产生)。
Demo on DB Fiddle : DB Fiddle 上的演示:
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
To return the difference between two date values in days you could use the DATEDIFF() Function, something like:要以天为单位返回两个日期值之间的差异,您可以使用 DATEDIFF() 函数,例如:
SELECT DATEDIFF(DAY, DayFrom, DayTo) AS 'DaysBetween'
FROM DateTable
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.