简体   繁体   中英

SQL query to take avg of column data into JSON for google pie chart in PHP

I need to create a SQL query and the PHP code to enter this data into JSON format for a pie chart using Google Charts API.

+--------+---------+---------+---------+
| City   | P1      | P10     | P25     |
+--------+---------+---------+---------+
|Dubai   |       45|      135|      136|
|SanDiego|       23|       34|       45|
|SanFran |       37|       39|       28|
+--------+---------+---------+---------+

This is the query I have already tried:

<?php
$rows2 = array();
$table2 = array();
$query2 = 'SELECT AVG(`P1`) AS avg_p1, AVG(`P10`) AS avg_p10, AVG(`P25`) (SELECT `P1`, `P10`, `P25` 
FROM `INFORMATION_SCHEMA`.`COLUMNS` AS pmname
WHERE `TABLE_SCHEMA`='g1109689' 
    AND `TABLE_NAME`='realtime') AS avg_p25 FROM `realtime` WHERE `City`="Dubai"';
$result2 = mysqli_query($conn, $query2);
$table2['cols'] = array(
 array(
  'label' => 'PM Type', 
  'type' => 'string'
 ),

 array(
  'label' => 'PM Number', 
  'type' => 'number'
 )
);

while($row2 = mysqli_fetch_array($result2))
{
 $sub_array2 = array();
 $sub_array2[] =  array(
      "v" => $row2["avg_p1"]
     );
$sub_array2[] =  array(
      "v" => $row2["avg_p10"]
     );
 $sub_array[] =  array(
      "v" => $row2["avg_p25"]
     );
 $rows2[] =  array(
     "c" => $sub_array2
    );
}
$table2['rows'] = $rows2;
echo $jsonTable2;
?>

I want the categories for the pie chart to be the averages of P1, P10, P25, respectively. So how do I create a SQL statement to select the averages and the name of the columns and how do I put that into a JSON table? Thanks!

I am guessing that you want average rowwise ie adding (p1+p10+p25)/3 for every city and not columnwise. So you can try the below query-

select city,(tablename.p1 + tablename.p10 + tablename.p25) / 3 as average from tablename

If you want to calculate avg columnwise for everycity you can use avg() method of sql.

select city, avg(p1),avg(p10),avg(p25) from tablename;

PS: you will only get name of one city if you use avg() function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM