如何从减去日期获得结果

时间:2016-04-05 15:07:41

标签: mysql sql

大家好我想查询当前日期减去上一个日期并使用SQL返回长度的变化(当前长度 - 前一个长度)。请参阅下表中当前减去前一长度

的变化样本

我无法想到查询如何做到这一点 SELECT日期,长度FROM length_data

date                 length          changes
-------------------  --------------  ------------
2000-08-29 10:30:00          147.98  147.98
2000-08-30 00:00:00          147.98  0
2000-09-02 10:30:00          156.51  8.53
2000-09-04 00:00:00          156.51  ....
2000-09-04 04:30:00          156.51  ....
2000-09-04 06:30:00          156.51  ....
2000-09-05 21:00:00          156.51
2000-09-06 03:00:00          156.51
2000-09-07 09:30:00          204.06
2000-09-07 10:30:00          204.06
2000-09-08 00:00:00          339.09
2000-09-08 12:30:00          395.78
2000-09-09 09:30:00          477.77
2000-09-10 02:30:00          737.77

2 个答案:

答案 0 :(得分:3)

您可以使用变量来模拟LAG窗口函数:

SELECT `date`, `length`,
       `length` - @prev AS changes,
       @prev := `length`
FROM length_data, (SELECT @prev := 0) AS a
ORDER BY `date`;

SqlFiddleDemo

我认为datePRIMARY KEY/UNIQUE,否则它就不会稳定。

修改

要删除其他列,您可以使用子查询。

SELECT `date`, `length`, `changes`
FROM (SELECT `date`, `length`,
        `length` - @prev AS changes,
        @prev := `length`
      FROM length_data,(SELECT @prev := 0) as a
      ORDER BY `date`) AS sub
ORDER BY `date`;  

SqlFiddleDemo2

输出:

╔══════════════════════════════╦═════════╦═════════╗
║            date              ║ length  ║ changes ║
╠══════════════════════════════╬═════════╬═════════╣
║ August, 29 2000 10:30:00     ║ 147.98  ║ 147.98  ║
║ August, 30 2000 00:00:00     ║ 147.98  ║ 0       ║
║ September, 02 2000 10:30:00  ║ 156.51  ║ 8.53    ║
║ September, 04 2000 00:00:00  ║ 156.51  ║ 0       ║
║ September, 04 2000 04:30:00  ║ 156.51  ║ 0       ║
║ September, 04 2000 06:30:00  ║ 156.51  ║ 0       ║
║ September, 05 2000 21:00:00  ║ 156.51  ║ 0       ║
║ September, 06 2000 03:00:00  ║ 156.51  ║ 0       ║
║ September, 07 2000 09:30:00  ║ 204.06  ║ 47.55   ║
║ September, 07 2000 10:30:00  ║ 204.06  ║ 0       ║
║ September, 08 2000 00:00:00  ║ 339.09  ║ 135.03  ║
║ September, 08 2000 12:30:00  ║ 395.78  ║ 56.69   ║
║ September, 09 2000 09:30:00  ║ 477.77  ║ 81.99   ║
║ September, 10 2000 02:30:00  ║ 737.77  ║ 260     ║
╚══════════════════════════════╩═════════╩═════════╝

编辑2:

使用Jean Doux's idea仅使用一列来计算它:

SELECT `date`, length,
    CAST((-IF(@prev IS NULL,0,@prev) + (@prev := length)) AS DECIMAL(10,4)) AS changes 
FROM length_data,(SELECT @prev := NULL ) AS a
ORDER BY `date`;

SqlFiddleDemo2

或最简单的方法是跳过应用程序层中的其他列。

答案 1 :(得分:1)

SELECT
date, 
length,
@prevLength - (@prevLength:= length) as changes
FROM 
test, (SELECT @prevLength:= 0) as a
ORDER BY account_id ASC, value ASC