大家好我想查询当前日期减去上一个日期并使用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
答案 0 :(得分:3)
您可以使用变量来模拟LAG
窗口函数:
SELECT `date`, `length`,
`length` - @prev AS changes,
@prev := `length`
FROM length_data, (SELECT @prev := 0) AS a
ORDER BY `date`;
的 SqlFiddleDemo
强>
我认为date
是PRIMARY 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