我有一张表随着时间的推移获得了测量结果。测量了一个参数。测量值来自通过IP地址和ID识别的仪表。 ID对于给定的IP是唯一的,因此仪表由IP-ID对唯一标识。我想知道在给定时间内所有仪表的测量值变化总和。
表格中的列是这样的:
val, meter_ip, meter_id, time_stamp
现在我正在使用两个查询计算一个给定仪表的变化:
SELECT val
FROM measurements
WHERE meter_ip=@ip AND meter_id=@id AND
time_stamp > DATE_SUB(now(), INTERVAL 1 WEEK)
ORDER BY time_stamp ASC
LIMIT 1
和
SELECT val
FROM measurements
WHERE meter_ip=@ip AND meter_id=@id AND
time_stamp > DATE_SUB(now(), INTERVAL 1 WEEK)
ORDER BY time_stamp DESC
LIMIT 1
然后我减去获得的值。 我确信这可以在一个SQL查询中完成,但我不知道该怎么做。首先,我正在寻找主要问题的解决方案,即总结所有仪表的差异。我想我需要通过IP和ID进行分组。
答案 0 :(得分:1)
如果保证每对都有一个唯一的time_stamp,你可以使用MIN()和MAX(),如下所示:
SELECT a.meter_ip, a.meter_id,
a.val, b.val, b.val - a.val as diff
FROM (select meter_ip, meter_id,
min(time_stamp) as min_time_stamp,
max(time_stamp) as max_time_stamp
FROM measurements
WHERE time_stamp > DATE_SUB(now(), INTERVAL 1 WEEK)
GROUP BY meter_ip, meter_id) c
INNER JOIN measurements a ON a.meter_ip = c.meter_ip and
a.meter_id = c.meter_id AND a.time_stamp = c.min_time_stamp
INNER JOIN measurements b ON b.meter_ip = c.meter_ip and
b.meter_id = c.meter_id AND b.time_stamp = c.max_time_stamp
但是,如果每个meter_ip,meter_id对可能有重复的time_stamp值,则此解决方案将不适合您