0

我和其他五个人坐在这里,尝试如何从列中汇总值。我们搜索了谷歌,但我们发现的代码都没有。

这是我的表格:

形式

这是我到目前为止的代码:

Public Class frmTotal
    Dim dt As New DataTable()
    Dim rowindex As Integer = 0
    Dim connstr As String = "provider=microsoft.jet.oledb.4.0;" & "data source=valleyfair.mdb"
    Dim sqlstr As String = "select * from employee"

    Private Sub btnTotal_Click(sender As System.Object, e As System.EventArgs) Handles btnTotal.Click

    End Sub

    Private Sub frmTotal_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        dt.Clear()
        Dim dataAdapter As New OleDb.OleDbDataAdapter(sqlstr, connstr)
        dataAdapter.Fill(dt)
        dataAdapter.Dispose()
    End Sub
End Class
4

2 回答 2

1

您可以在 TSQL 或代码中求和。这是 TSQL 版本:

select *, SUM(MyColumnName) AS TotalMyColumnName
from employee

如果您只想要总和,则只检索总和而不是其他列

select SUM(MyColumnName) AS TotalMyColumnName
from employee
于 2013-05-08T23:46:34.907 回答
0

我是 SQL 的新手,但这是我想象的一种方法: 1:声明需要的变量。2:从数据库中获取需要的数据并保存在数据库容器中。该代码仅获取列salary 中的值。(不确定你给它起什么名字,但你可以编辑它) 3:使用 for 循环将所有数字相加。

如果您使用的是 oleDB,只要它对 OleDB 说 SQL 就进行更改,它应该可以正常工作

Dim Result As Integer = 0
Dim salaryDB As New DataTable
Dim sSQL As String = String.Empty
Dim conn As New SqlClient.SqlConnection
Dim cmd As New SqlClient.SqlCommand
Dim da As New SqlClient.SqlDataAdapter

Public Sub GetSum()
    Try
        conn = New SqlClient.SqlConnection(Constr) 
        conn.Open()
        cmd.Connection = conn
        cmd.CommandType = CommandType.Text
        sSQL = "SELECT salary FROM Employee"
        cmd.CommandText = sSQL
        da.SelectCommand = cmd
        da.Fill(salaryDB)
        If dtActive.Rows.Count = 0 Then
            MsgBox("No record found!")
        End If
    Catch ex As Exception
        MsgBox(ErrorToString)
    Finally
        conn.Close()
    End Try
    For Each Row As DataRow In salaryDB.Rows
        Result = Result + row(0) 'row is the current row selected and 0 is the column number
    Next
End Sub
于 2013-08-09T07:09:57.170 回答