我一直试图"在日期合并数组"将数据显示到Google柱形图中。我想按年/月分组问题列表和成本。这是我的数据
array
0 =>
array
'date' => string '2017-03'
'source' => string 'Problem 1'
'cost' => float 135
1 =>
array
'date' => string '2017-03'
'source' => string 'Problem 2'
'cost' => float 385
2 =>
array
'date' => string '2017-04'
'source' => string 'Problem 3'
'cost' => float 3500
3 =>
array
'date' => string '2017-04'
'source' => string 'Problem 1'
'cost' => float 4437.5
4 =>
array
'date' => string '2017-04'
'source' => string 'Problem 2'
'cost' => float 318
所需的输出为https://jsfiddle.net/9d1fzsaf/1/
如果通过MySQL group by Date和问题源获取数据,我应该优化查询吗?
SELECT DATE_FORMAT(creation_date,'%Y-%m') AS date,
( CASE
WHEN source_problem = '0' THEN 'Empty'
WHEN source_problem = '1' THEN 'Problem 1'
WHEN source_problem = '2' THEN 'Problem 2'
WHEN source_problem = '3' THEN 'Problem 3'
ELSE 'Others'
END ) AS source,
SUM(aprox_cost) AS cost
FROM table
WHERE source_problem IS NOT NULL
GROUP BY DATE_FORMAT(creation_date,'%Y-%m'),
source_problem
任何帮助都将受到高度赞赏! 谢谢
答案 0 :(得分:0)
我修改了你的mysql查询。请使用此代码
SELECT DATE_FORMAT(creation_date,'%Y-%m') AS date,
( CASE
WHEN source_problem = '0' THEN 'Empty'
WHEN source_problem = '1' THEN 'Problem 1'
WHEN source_problem = '2' THEN 'Problem 2'
WHEN source_problem = '3' THEN 'Problem 3'
ELSE 'Others'
END ) AS source,
SUM(aprox_cost) AS cost
FROM table
HAVING source_problem IS NOT NULL
GROUP BY date;
答案 1 :(得分:0)
为了在张贴的小提琴中制作图表,
每个source_problem
都需要是一个单独的列
建议将sql中的列分开...
SELECT
DATE_FORMAT(creation_date,'%Y-%m') AS Month,
SUM(CASE
WHEN source_problem = '0'
THEN aprox_cost
ELSE 0
END) AS Empty,
SUM(CASE
WHEN source_problem = '1'
THEN aprox_cost
ELSE 0
END) AS Problem1,
SUM(CASE
WHEN source_problem = '2'
THEN aprox_cost
ELSE 0
END) AS Problem2,
SUM(CASE
WHEN source_problem = '3'
THEN aprox_cost
ELSE 0
END) AS Problem3,
SUM(CASE
WHEN source_problem <> '0' AND source_problem <> '1' AND source_problem <> '2' AND source_problem <> '3'
THEN aprox_cost
ELSE 0
END) AS Others
FROM
table
WHERE
source_problem IS NOT NULL
GROUP BY
DATE_FORMAT(creation_date,'%Y-%m')
另外,在使用JSON数据时,它需要位于this format,
为了直接创建数据表......
var data = new google.visualization.DataTable(jsonData);
因此,构建类似于以下结果...
$data = array();
$data['cols'] = array(
array('label' => 'Month', 'type' => 'string')
array('label' => 'Empty', 'type' => 'number')
array('label' => 'Problem 1', 'type' => 'number')
array('label' => 'Problem 2', 'type' => 'number')
array('label' => 'Problem 3', 'type' => 'number')
array('label' => 'Others', 'type' => 'number')
);
$data['rows'] = array();
foreach ($results as $result) {
$row = array(
array('v' => (string) $result['Month'])
array('v' => (float) $result['Empty'])
array('v' => (float) $result['Problem1'])
array('v' => (float) $result['Problem2'])
array('v' => (float) $result['Problem3'])
array('v' => (float) $result['Others'])
);
$data['rows'][] = array('c' => $row);
}
echo json_encode($data);