您好我有以下查询显示以下结果:
SELECT
meter.meter_serial,
her060.node_address,
her060.report_time,
her060.node_reading
FROM
meter,
her060
WHERE meter.node_address = her060.node_address
AND meter.meter_serial = '31602193'
ORDER BY her060.report_time DESC
LIMIT 10
结果很好:
meter_serial node_address report_time node_reading
31602193 10164d995147 10/01/2014 0:36 777
31602193 10164d995147 8/01/2014 18:22 763
31602193 10164d995147 7/01/2014 6:04 724
31602193 10164d995147 6/01/2014 12:19 698
31602193 10164d995147 4/01/2014 23:55 669
31602193 10164d995147 3/01/2014 11:30 650
31602193 10164d995147 1/01/2014 23:06 624
31602193 10164d995147 31/12/2013 10:41 624
31602193 10164d995147 29/12/2013 22:17 624
31602193 10164d995147 28/12/2013 9:53 624
但我想添加另一列来计算node_readings之间的差异。
有人可以建议做什么吗?
另请原谅我的格式,这是我的第一个问题:)
提前感谢
答案 0 :(得分:1)
SELECT
meter.meter_serial,
her060.node_address,
her060.report_time,
her060.node_reading,
@previous - node_reading AS your_difference, /*here the variable holds the value of the previous row*/
@previous := node_reading /*here the variable gets assigned the value of the current row*/
FROM
meter
INNER JOIN her060 ON meter.node_address = her060.node_address
CROSS JOIN (SELECT @previous := (SELECT node_reading FROM her060 ORDER BY report_time DESC LIMIT 1)) variable_initialization_query_alias
WHERE
meter.meter_serial = '31602193'
ORDER BY her060.report_time DESC
LIMIT 10
答案 1 :(得分:0)
对此列使用自动增量字段或唯一键,以便您可以减去上一行值。
**SELECT meter.meter_serial,
her060.node_address,
her060.report_time,
her060.node_reading ,
a.node_reading -b.node_reading
FROM
meter,
her060 a
inner join
her060
on a.id = b.id -1
WHERE meter.node_address = her060.node_address
AND meter.meter_serial = '31602193'
ORDER BY her060.report_time DESC
LIMIT 10**