sql查询行之间的差异

时间:2018-07-25 16:16:35

标签: mysql sql date rdbms

我有一个带有日期的表,我想将第一个日期与第二个日期相减,第二个日期与第三个日期相减,依此类推,直到最后一个n-1与n相减。

如何为此编写查询?

该表将被称为Random,列名称为date

 date       
+------------+
| 2009-06-20 |
| 2010-02-12 |
| 2012-03-14 |
| 2013-09-10 |
| 2014-01-01 |
| 2015-04-10 |
| 2015-05-01 |
| 2016-01-01 |
+------------+

3 个答案:

答案 0 :(得分:0)

您需要获取下一个日期。我将使用相关的子查询:

select t.date,
       (select min(t2.date)
        from t t2
        where t2.date > t.date
       ) as next_date
from t;

您只需要使用datediff()就能获得天数差异。

答案 1 :(得分:0)

使用ROW_NUMBER 对于行编号,然后使用子查询来计算差异

SELECT  column_date 
,DATEDIFF( D , column_date 
,(SELECT column_date FROM
    (
    SELECT  column_date , ROW_NUMBER() OVER ( ORDER BY column_date) AS RowMum
     FROM table_Random AS tBL_1
    ) AS tbl_2
       WHERE tbl_2.RowMum= tBL_1.RowMum-1
 )
         ) DIFF
FROM 
(
SELECT  column_date , ROW_NUMBER() OVER ( ORDER BY column_date) AS RowMum
FROM table_Random
) AS tBL_1

答案 2 :(得分:-1)

当我第一次写答案时,我没有注意到mysql标记,所以现在用指向MySQL 8.0的小提琴的链接进行更新

https://www.db-fiddle.com/f/myUJYeFrMXmU1piQXAmnv4/0

/* tested against MySQL v8.0 */
WITH T(d) AS (
    SELECT '2009-06-20' as d 
    UNION
    SELECT '2010-02-12'
    UNION
    SELECT '2012-03-14'
    UNION
    SELECT '2013-09-10'
    UNION
    SELECT '2014-01-01'
    UNION
    SELECT '2015-04-10'
    UNION
    SELECT '2015-05-01'
    UNION
    SELECT '2016-01-01'
), LAGGED(d, next_d) AS (
    SELECT d, LEAD(d) OVER (ORDER BY d ASC) AS next_d
    FROM T
)
/* datediff args are in opposite order to SQL server.  Also,
  only day part is considered */
SELECT l.d, l.next_d, DATEDIFF(l.next_d, l.d) AS n_days
 FROM LAGGED AS l

这是我针对SQL Server的原始答案:

WITH T(d) AS (
  SELECT d FROM (
  VALUES 
  ('2009-06-20'),
  ('2010-02-12'),
  ('2012-03-14'),
  ('2013-09-10'),
  ('2014-01-01'),
  ('2015-04-10'),
  ('2015-05-01'),
  ('2016-01-01')
  ) AS T1(d)
), LAGGED(d, next_d) AS (
   SELECT d, LEAD(d) OVER (ORDER BY d ASC) AS next_d
   FROM T
)
SELECT l.d, l.next_d, DATEDIFF(DAY, l.d, l.next_d) AS n_days
FROM LAGGED AS l

并生成此输出(以我做过的繁琐的手工编辑为模):

 
  d              next_d     n_days
  2009-06-20    2010-02-12  237
  2010-02-12    2012-03-14  761
  2012-03-14    2013-09-10  545
  2013-09-10    2014-01-01  113
  2014-01-01    2015-04-10  464
  2015-04-10    2015-05-01  21
  2015-05-01    2016-01-01  245
  2016-01-01    NULL    NULL