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

时间:2018-05-24 11:45:08

标签: sql vb.net pie-chart

所以我创建了一个饼图,它会计算列中项目的数量,问题是它还会计算空项目,我可以使查询不计算仅在一列上的空值,它显示什么时候我没有计算超过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

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

1 个答案:

答案 0 :(得分:0)

这是我所描述的快速检查。

假设该表包含以下信息: enter image description here

运行查询:

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

我们最终得到以下结果:

enter image description here

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

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

    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"

请使用以下图表离开我们:

enter image description here