"time" "id", "parameter", "value" "2014-02-18 18:58:00", "1$SGP", "A", "415.7806091308594" "2014-02-18 18:58:00", "1$SGP", "B", "240.3373565673828" "2014-02-18 18:58:00", "2$SGP", "A", "393.191162109375" "2014-02-18 18:58:00", "2$SGP", "B", "50.10090637207031" "2014-02-18 18:58:00", "3$SGP", "E", "3484841472" "2014-02-18 18:05:01", "1$SGP", "A", "0" "2014-02-18 17:58:01", "1$SGP", "B", "0" "2014-02-18 17:58:01", "2$SGP", "C", "0" "2014-02-18 17:58:01", "2$SGP", "D", "0" "2014-02-18 17:58:01", "2$SGP", "E", "3061691904" "2014-02-18 17:57:01", "3$SGP", "A", "0" "2014-02-18 17:57:02", "3$SGP", "B", "0"
现在从Foo表中得到上述数据,我需要为所有不同的ID添加参数“A”的值,这样对于特定ID,它会从上一个时间戳中获取值。 18:00:00和19:00:00如何在考虑时间和id字段的情况下快速编写针对此要求的单个查询。
答案 0 :(得分:0)
认为你会挣扎,因为你想要提取,但你正在索引一个日期/时间字段。
但是这样的事情应该这样做: -
SELECT SUM(value)
FROM foo
INNER JOIN
(
SELECT id, MAX(`time`) AS maxtime
FROM foo
WHERE TIME(`time`) BETWEEN '18:00:00' AND '19:00:00'
AND parameter = 'A'
GROUP BY id
) sub1
ON foo.id = sub1.id
AND foo.`time` = sub1.maxtime