Mysql 带日期的表,然后是下一个日期

Mysql 带日期的表,然后是下一个日期,mysql,sql,Mysql,Sql,在给定一些条件的情况下,我希望生成一个表,其中一个日期后跟集合中的下一个日期 原始数据: id date 1 2000-01-01 1 2000-01-02 1 2000-01-04 1 2000-01-10 1 2000-01-14 1 2000-01-15 1 2000-01-16 1 2000-01-18 2 2000-02-01 2 2000-02-02 2 2000-02-04 2

在给定一些条件的情况下,我希望生成一个表,其中一个日期后跟集合中的下一个日期

原始数据:

id       date
1     2000-01-01
1     2000-01-02
1     2000-01-04
1     2000-01-10
1     2000-01-14
1     2000-01-15
1     2000-01-16
1     2000-01-18
2     2000-02-01
2     2000-02-02
2     2000-02-04
2     2000-02-10
2     2000-02-14
2     2000-02-15
2     2000-02-16
2     2000-02-18
将导致:

   id       date           date
    1     2000-01-01    2000-01-02
    1     2000-01-02    2000-01-04
    1     2000-01-04    2000-01-10
    1     2000-01-10    2000-01-14
    1     2000-01-14    2000-01-15
    1     2000-01-15    2000-01-16
    1     2000-01-16    2000-01-18
    1     2000-01-18    NULL
    2     2000-02-01    2000-02-02
    2     2000-02-02    2000-02-04
    2     2000-02-04    2000-02-10
    2     2000-02-10    2000-02-14
    2     2000-02-14    2000-02-15
    2     2000-02-15    2000-02-16
    2     2000-02-16    2000-02-18
    2     2000-02-18    NULL

我知道我必须使用自联接,但是我不知道如何返回顺序上的下一个最大值,因为给定了特定的id。谢谢

在大多数数据库中,您可以只使用
lead()
函数。在MySQL中,最简单的方法可能是关联子查询:

select t.*,
       (select t2.date
        from rawdata t2
        where t2.id = t.id and t2.date > t.date
        order by t2.date
        limit 1
       ) as next_date
from rawdata t;

如果是mysql或postgresql数据库,可以使用[date+interval 1 day]

例如:

select t.id, t.date, t.date + interval 1 days as date 2 from rawdata t;
对于oracle,您可以执行以下操作:

select t.id , t.date, TO_DATE(t.date, 'YYYY-MM-DD') + 1 from rawdata t;

并将子查询排序并限制为1行?按t2添加
订单。日期限制1
我认为这似乎只是从id范围返回最大值,而不仅仅是下一个最高日期值。@TomKrakov。该
desc
应该是
asc
。但日期的差异有所不同,这就是为什么我无法添加标准的1天。