创建一个将计算多列的饼图 sql vb.net

Create a pie chart that will count multiple columns sql vb.net

所以我正在创建一个饼图来计算一列中的项目数,问题是它也计算空项目,我可以使查询不只在一列上计算空值,它显示当我让它不计算超过 1 列的空值时什么也没有。当一行在多个列上有一个值时,例如第 1 行在 violation1 和 violation2 上有一个值,饼图中会有一部分将它们都计为一个新值。

这是我的代码 -

    Dim cnn3 As New SqlConnection
    Dim cmd3 As New SqlCommand
    Dim dr As SqlDataReader
    Try
        cnn3.ConnectionString = Login.sqlcode
        cmd3.Connection = cnn3
        Dim tblFields As String = "SELECT count(*) as [Vio] from Violations WHERE Violation1<> '" & "NULL" & "' Group by Violation1, Violation2, Violation3, Violation4, Violation5, Violation6, Violation7, Violation8"
        Dim oData As New SqlDataAdapter(tblFields, cnn3)
        Dim ds As New DataSet
        Dim oCmd As New SqlCommand(tblFields, cnn3)
        cnn3.Open()
        oData.Fill(ds, "Violations")
        cnn3.Close()
        Chart1.DataSource = ds.Tables("Violations")
        Dim Series1 As Series = Chart1.Series("Series1")
        Series1.Name = "Violations"
        Chart1.Series(Series1.Name).YValueMembers = "Vio"
        Chart1.Size = New System.Drawing.Size(780, 350)
    Catch ex As Exception
        MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
    End Try

我认为问题出在查询中,我在这里试图实现的是饼图显示列 violation1-8 的计数,没有空值,也没有组合值。

下面是我所描述内容的快速检查。

假设 table 包含以下信息:

通过运行查询:

SELECT Count(Violation1) AS Violation1,
       Count(Violation2) AS Violation2,
       Count(Violation3) AS Violation3,
       Count(Violation4) AS Violation4,
       Count(Violation5) AS Violation5
FROM Violations

我们最终得到以下结果:

将这些结果放入数据集后,可以很容易地显示图表。

在这里,我们使用从查询结果中填充的数据集填充图表。

    Chart1.Series.Clear()
    Chart1.Series.Add("Series1")
    'we only have one row so we only need to loop through the columns
    'of our row (Rows(0))  
    For Each c As DataColumn In ds.Tables(0).Columns
        Chart1.Series(0).Points.AddXY(c.ColumnName, ds.Tables(0).Rows(0).Item(c.ColumnName).ToString)
    Next
    Chart1.Series(0).ChartType = DataVisualization.Charting.SeriesChartType.Pie
    Chart1.Series(0).IsValueShownAsLabel = True 'show the value of each "slice"

给我们留下下图: