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
/* 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
3条答案
按热度按时间fcg9iug31#
使用行编号进行行编号,然后使用子查询计算差异
0aydgbwb2#
你需要下次约会。我将使用相关子查询:
你只需要使用
datediff()
在几天内得到差别。6pp0gazn3#
当我第一次写我的答案时,我没有注意到mysql标签,所以我现在用链接mysql 8.0 fiddle来更新它
https://www.db-fiddle.com/f/myujyefrmxmu1piqxamnv4/0
以下是我针对sql server的原始答案:
并产生这个输出(以我所做的繁琐手工编辑为模):