Domanda

"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"

Now from say the table Foo having the above data, I need to add up the value of parameter "A" for all the different IDs such that for a particular ID it picks up the value from the last time stamp that came between 18:00:00 and 19:00:00. How to write a single Query for this requirement that is fast considering both time and id field are indexed.

È stato utile?

Soluzione

Think you will struggle as you want to extract by the time, yet you are indexing a date / time field.

However something like this should do it:-

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top