使用VB从Access数据库中检索一列工资的总和

时间:2013-05-08 23:43:41

标签: vb.net visual-studio-2010 dataset oledb

我和其他五个人一起坐在这里试着如何从一个列中获得总值。我们已经搜索过Google,但我们发现的代码都没有。

这是我的表格:

form

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

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

2 个答案:

答案 0 :(得分:1)

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

select *, SUM(MyColumnName) AS TotalMyColumnName
from employee

如果你只想要总和那么只检索总和而不是其他列

select SUM(MyColumnName) AS TotalMyColumnName
from employee

答案 1 :(得分:0)

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

如果你正在使用oleDB,那么每当它说SQL to OleDB时它就会改变,它应该只是相同的

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