行间差异的sql查询

chhqkbe1  于 2021-06-20  发布在  Mysql
关注(0)|答案(3)|浏览(266)

我有一个表,里面有日期,我想用第二个减去第一个日期,用第二个减去第二个,用第三个,依此类推,直到最后一个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 |
+------------+
fcg9iug3

fcg9iug31#

使用行编号进行行编号,然后使用子查询计算差异

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
0aydgbwb

0aydgbwb2#

你需要下次约会。我将使用相关子查询:

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

你只需要使用 datediff() 在几天内得到差别。

6pp0gazn

6pp0gazn3#

当我第一次写我的答案时,我没有注意到mysql标签,所以我现在用链接mysql 8.0 fiddle来更新它
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

相关问题