来自MySQL和PHP的谷歌条形图

时间:2014-03-12 21:21:01

标签: php mysql google-visualization

我正在尝试使用从MySQL数据库中提取的数据创建一个简单的Google条形图。谷歌提供an example,我试图将其构建起来。请参阅“简单示例”。

我希望能够显示每所学校的男性和女性总人数。

这是我从MySQL中检索数据的PHP代码:

<?php
$pdo=new PDO("mysql:dbname=trek;host=localhost","USERNAME","PASSWORD");
$stmt=$pdo->prepare("SELECT school, gender, count(*) as count from participant group by     school, gender;");
$stmt->execute();
$results=$stmt->fetchALL(PDO::FETCH_ASSOC);
echo json_encode($results);
?>

返回:

[
{
 school: "School A",
 gender: "F",
 count: "1"
},
{
 school: "School A",
 gender: "M",
 count: "2"
},
{
 school: "School B",
 gender: "M",
 count: "2"
},
{
 school: "School B",
 gender: "F",
 count: "10"
}
]

但是我需要以下列格式出现:

[
{
 school: "School A",
 m: "2",
 f: "1"
},
{
 school: "School B",
 m: "2",
 f: "2"
}
]

在使用Google Charts时,我有点新意,我愿意接受任何建议。

提前致谢!

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT
  school,
  sum(if(gender='M',1,0)) as m,
  sum(if(gender='F',1,0)) as f
FROM
  participant
GROUP BY
  school

答案 1 :(得分:0)

我明白了。问题出在我的SQL语句

SELECT school, 
  sum(case when gender = 'm' then 1 else 0 end) male,
  sum(case when gender = 'f' then 1 else 0 end) female
FROM participant 
GROUP BY school;