简体   繁体   English

SQL 查询将列数据的平均值输入 JSON 用于 PHP 中的谷歌饼图

[英]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. 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.我希望饼图的类别分别是 P1、P10、P25 的平均值。 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?那么如何创建 SQL 语句到 select 的平均值和列的名称以及如何将其放入 JSON 表中? Thanks!谢谢!

I am guessing that you want average rowwise ie adding (p1+p10+p25)/3 for every city and not columnwise.我猜你想要按行平均,即为每个城市添加(p1+p10+p25)/3而不是按列。 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.如果要按列计算每个城市的 avg,可以使用 sql 的avg()方法。

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

PS: you will only get name of one city if you use avg() function PS:如果你使用 avg() function,你只会得到一个城市的名字

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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