You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将SQL Server分组数据通过Chart.js/Google Chart展示为柱状图

SQL Server分组数据渲染柱状图实现方案

整体实现逻辑非常直接,你已经完成了SQL Server数据查询的核心步骤,只需要将分组查询得到的结果序列化为JSON格式,供给前端图表库读取渲染即可,不需要依赖额外第三方API。

通用后端数据预处理步骤

  • 首先编写分组查询SQL,示例按业务维度分组统计的语句:
SELECT 分组维度字段, SUM(统计字段) AS 统计值 FROM 你的表名 WHERE 筛选条件 GROUP BY 分组维度字段
  • 将查询得到的DataTable结果序列化为JSON数组,返回给前端,标准返回格式示例:
[{"category":"维度1","value":1200},{"category":"维度2","value":960},{"category":"维度3","value":1580}]

如果是ASP.NET栈(你提到的GridView为.NET常用控件),可以用Newtonsoft.Json库快速完成序列化。


方案1:使用Chart.js实现柱状图

前端代码示例:

<!-- 页面先引入Chart.js库 -->
<canvas id="barChart" width="800" height="400"></canvas>
<script>
// 请求后端接口拿分组数据
fetch('/api/getGroupData')
  .then(res => res.json())
  .then(data => {
    // 处理成Chart.js需要的格式
    const categories = data.map(item => item.category)
    const values = data.map(item => item.value)
    // 初始化柱状图
    new Chart(document.getElementById('barChart'), {
      type: 'bar',
      data: {
        labels: categories,
        datasets: [{
          label: '统计值',
          data: values,
          backgroundColor: 'rgba(54, 162, 235, 0.6)'
        }]
      },
      options: {
        scales: {
          y: { beginAtZero: true }
        }
      }
    })
  })
</script>

方案2:使用Google Chart实现柱状图

前端代码示例:

<!-- 引入Google Chart库 -->
<div id="barChart" style="width: 800px; height: 400px;"></div>
<script>
google.charts.load('current', {packages: ['corechart']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
  fetch('/api/getGroupData')
    .then(res => res.json())
    .then(data => {
      // 转换为Google Chart需要的二维数组格式
      const chartData = [['分组维度', '统计值']]
      data.forEach(item => {
        chartData.push([item.category, item.value])
      })
      const dataTable = google.visualization.arrayToDataTable(chartData)
      const options = {
        title: '分组统计柱状图',
        legend: { position: 'none' }
      }
      const chart = new google.visualization.ColumnChart(document.getElementById('barChart'))
      chart.draw(dataTable, options)
    })
}
</script>

内容的提问来源于stack exchange,提问作者AEC Production

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 18:30:05