I have the following query:
$strQuery = "SELECT siteid, SUM(watts) AS wattage, unit, device, time FROM inverter WHERE siteid = '528' AND time Between '$time1' AND '$time2' Order By device Asc";
I’m making a graph in fusion charts and need the total watts for each device but when i do the query above it takes all values and places them for just the first device. I have 40 devices and need each one to have its total watts produced.
On the chart i am displaying device as the x axis name label and the wattage as the value.
Thanks
SUM()is an aggregate function which should be used together with aGROUPstatement. IfGROUPstatement is omitted, all selected rows are aggregated as a group.see docs: http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html
Look into
GROUP BYstatement:Also, when you use aggregation and select fields that are not contained in the
GROUPstatement (here: time) you must make sure you really get the value you want.The values of the aggregated row you get for each device are calculated using many rows with possibly individual values in those fields. When you don’t use an aggregate function (
MIN,MAX,AVG, ..) to determine which of the multiple values your aggregated row should contain, you will receive a value selected more or less selected randomly by MySQL.You should either
MIN,MAX,AVG, ..) for each field that is not contained in the GROUP BY clause to ensure you get the right value. (here i inserted both start and end time for the measure timespan usingMINandMAX)GROUP BYclause(i did that for “unit” in the example, because you get a wrong result when using
SUMon both megawatts and kilowatts .. i assume that is what you use “unit” for?)Again: Otherwise the resulting value in such fields is random and not deterministic.