首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

MySQL/JS 構建完整時間序列:填充缺失月份為 0 供 Highcharts 使用

     編輯:程式設計疑難解答

方案一:JavaScript 端填充(推薦)

// 後端返回原始數據 [{month:1, status:'成功', count:3}, ...]
const months = Array.from({length:12}, (_,i)=>i+1);
const statuses = ['成功','失敗'];
// 初始化全零結構
const data = {};
months.forEach(m => {
    data[m] = {};
    statuses.forEach(s => data[m][s] = 0);
});
// 填充實際數據
rawData.forEach(r => data[r.month][r.status] = r.count);
// 轉換為 Highcharts 所需系列
const series = statuses.map(s => ({
    name: s,
    data: months.map(m => data[m][s])
}));

方案二:MySQL 生成完整序列 (8.0+)

WITH RECURSIVE m AS (
    SELECT 1 AS month UNION ALL SELECT month+1 FROM m WHERE month<12
), s AS (
    SELECT '成功' AS status UNION ALL SELECT '失敗'
)
SELECT m.month, s.status, COALESCE(t.cnt,0) AS count
FROM m CROSS JOIN s
LEFT JOIN (
    SELECT month, status, COUNT(*) cnt FROM `table` GROUP BY month, status
) t ON m.month=t.month AND s.status=t.status
ORDER BY m.month, s.status;

選型建議

前端填充靈活、減輕數據庫壓力;後端填充適合報表服務直出。Highcharts 直接消費 series 陣列。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved