我想计算连续行中两个值的差异。 例如:计算前一天燃油价格的差异。如何使用SQL查询解决这个问题(值如下)。请帮助我
Date Speed Petrol Diesel
2018-04-01 79.22 76.41 68.89
2018-04-02 79.32 76.52 69.01
2018-04-04 79.45 76.64 69.15
2018-04-05 79.48 76.67 69.18
2018-04-06 79.48 76.67 69.21
2018-04-07 79.5 76.69 69.25
2018-04-08 79.53 76.72 69.3
2018-04-09 79.49 76.69 69.27
2018-04-10 79.48 76.67 69.3
2018-04-11 79.48 76.67 69.3
2018-04-12 79.44 76.63 69.27
2018-04-13 79.4 76.6 69.3
答案 0 :(得分:1)
如果您没有支持窗口函数的版本,您可以使用子查询来获取昨天的价格
select `date`,speed,
speed - ifnull((select speed from t t1 where t1.date < t.date order by t1.date desc limit 1),speed) yesterdayspeed,
petrol,
petrol - ifnull((select petrol from t t1 where t1.date < t.date order by t1.date desc limit 1),petrol) yesterdayspetrol,
diesel,
diesel - ifnull((select diesel from t t1 where t1.date < t.date order by t1.date desc limit 1),diesel) yesterdaysdiesel
from t;
+------------+-------+----------------+--------+------------------+--------+------------------+
| date | speed | yesterdayspeed | petrol | yesterdayspetrol | diesel | yesterdaysdiesel |
+------------+-------+----------------+--------+------------------+--------+------------------+
| 2018-04-01 | 79.22 | 0.00 | 76.41 | 0.00 | 68.89 | 0.00 |
| 2018-04-02 | 79.32 | 0.10 | 76.52 | 0.11 | 69.01 | 0.12 |
| 2018-04-04 | 79.45 | 0.13 | 76.64 | 0.12 | 69.15 | 0.14 |
| 2018-04-05 | 79.48 | 0.03 | 76.67 | 0.03 | 69.18 | 0.03 |
| 2018-04-06 | 79.48 | 0.00 | 76.67 | 0.00 | 69.21 | 0.03 |
| 2018-04-07 | 79.50 | 0.02 | 76.69 | 0.02 | 69.25 | 0.04 |
| 2018-04-08 | 79.53 | 0.03 | 76.72 | 0.03 | 69.30 | 0.05 |
| 2018-04-09 | 79.49 | -0.04 | 76.69 | -0.03 | 69.27 | -0.03 |
| 2018-04-10 | 79.48 | -0.01 | 76.67 | -0.02 | 69.30 | 0.03 |
| 2018-04-11 | 79.48 | 0.00 | 76.67 | 0.00 | 69.30 | 0.00 |
| 2018-04-12 | 79.44 | -0.04 | 76.63 | -0.04 | 69.27 | -0.03 |
| 2018-04-13 | 79.40 | -0.04 | 76.60 | -0.03 | 69.30 | 0.03 |
+------------+-------+----------------+--------+------------------+--------+------------------+
12 rows in set (0.00 sec)
答案 1 :(得分:0)
因为这对我来说似乎有些商业逻辑。最好在你的代码中执行此操作,而不是在我相信的sql查询中。
您可以获取行对象列表中的所有数据,但可以找到差异。
答案 2 :(得分:0)
看起来是在MySQL 8.0中使用新窗口函数的好机会
假设其中一个与燃油价格有关,您希望按日期按升序排列结果,以及一个看起来像这样的表
CREATE TABLE tspeed (
`id` INT auto_increment primary key,
`Date` DATE NOT NULL,
`Speed` DECIMAL(5,2),
`Petrol` DECIMAL(5,2),
`Diesel` DECIMAL(5,2)
);
您可以使用LAG()函数来获取任何列的差异。
e.g。
SELECT `id`, `Date`, `Speed`,
LAG(`Speed`) OVER w AS 'Prev Speed',
`Speed` - LAG(`Speed`) OVER w AS 'Diff Speed',
`Petrol`,
LAG(`Petrol`) OVER w AS 'Prev Petrol',
`Petrol` - LAG(`Petrol`) OVER w AS 'Diff Petrol',
`Diesel`,
LAG(`Diesel`) OVER w AS 'Prev Diesel',
`Diesel` - LAG(`Diesel`) OVER w AS 'Diff Diesel'
FROM tspeed
WINDOW w AS (ORDER BY `Date` ASC);