我的用例是使用存储在MySQL中的日志表创建stacked column graph。
目前我有一个常规的柱形图,但我希望按site_id
汇总数据,以便我可以看到该栏的哪些部分归因于哪个网站。
我现有柱形图的当前技术是获取日期列表,并在按日期分组时计算记录。然后我使用for循环创建我需要的14天时间段,然后循环我的数据以将匹配计数填充到正确的日期。
SELECT DATE(`created`) AS `day`,
COUNT(`id`) AS `count`
FROM `api_logs` `ApiLogs`
WHERE DATE(created) BETWEEN DATE_SUB(CURDATE(), INTERVAL 14 day) AND CURDATE()
GROUP BY DATE(`created`)
ORDER BY DATE(`created`)
对于堆叠图表,我想不出一种方法来整理MySQL中的数据而不执行大量查询或构建子查询来整理每个站点的计数。
是否存在查询结果的既定模式,该结果易于与堆积柱形图兼容?
如果有任何查询后处理解决方案,我的前端是用PHP构建的。
答案 0 :(得分:1)
问题是您需要为每个站点添加一列
如果您有一定数量的站点,那么您可以在sql中手动构建列
SELECT DATE(`created`) AS `day`,
SUM(CASE WHEN `site_id` = 'A' THEN 1 ELSE 0 END) AS `site A`,
SUM(CASE WHEN `site_id` = 'B' THEN 1 ELSE 0 END) AS `site B`
FROM `api_logs` `ApiLogs`
WHERE DATE(created) BETWEEN DATE_SUB(CURDATE(), INTERVAL 14 day) AND CURDATE()
GROUP BY DATE(`created`)
ORDER BY DATE(`created`)
否则,您可以动态构建列并聚合
使用谷歌的DataView和data.group
首先,将site_id
添加到sql
SELECT DATE(`created`) AS `day`,
`site_id` AS `site_id`,
COUNT(`id`) AS `count`
FROM `api_logs` `ApiLogs`
WHERE DATE(created) BETWEEN DATE_SUB(CURDATE(), INTERVAL 14 day) AND CURDATE()
GROUP BY DATE(`created`), `site_id`
ORDER BY DATE(`created`), `site_id`
应该产生,类似于以下......
['Date', 'Site', 'Count'],
[new Date('11/17/2016'), 'A', 10],
[new Date('11/17/2016'), 'B', 15],
[new Date('11/17/2016'), 'C', 22],
请参阅以下工作代码段以动态构建列...
google.charts.load('current', {
callback: function () {
// raw table data
var data = google.visualization.arrayToDataTable([
['Date', 'Site', 'Count'],
[new Date('11/17/2016'), 'A', 10],
[new Date('11/17/2016'), 'B', 15],
[new Date('11/17/2016'), 'C', 22],
[new Date('11/17/2016'), 'D', 8],
[new Date('11/16/2016'), 'A', 12],
[new Date('11/16/2016'), 'B', 6],
[new Date('11/16/2016'), 'C', 13],
[new Date('11/16/2016'), 'E', 14],
[new Date('11/15/2016'), 'A', 9],
[new Date('11/15/2016'), 'B', 16],
[new Date('11/15/2016'), 'D', 11]
]);
// create view with columns for each site, then agg view
var view = new google.visualization.DataView(data);
var aggColumns = [];
var viewColumns = [0];
data.getDistinctValues(1).forEach(function (site, index) {
viewColumns.push({
calc: function (dt, row) {
if (dt.getValue(row, 1) === site) {
return dt.getValue(row, 2);
}
return null;
},
label: site,
type: 'number'
});
aggColumns.push({
aggregation: google.visualization.data.sum,
column: index + 1,
label: site,
type: 'number'
});
});
view.setColumns(viewColumns);
var group = google.visualization.data.group(
view,
[0],
aggColumns
);
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(group, {
isStacked: true
});
},
packages: ['corechart']
});

<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
&#13;