|
-
Oct 15th, 2009, 07:03 AM
#1
Thread Starter
Hyperactive Member
[RESOLVED] Finding the Sum of the Data in a Column
Ok, I'm throwing my last idea out...
Just have a simple question.
I'm connected to an access database using VB 2008.. there is information already located in the tables. But what I am looking to do, is find the "SUM" of all the data in a certain column.
Any ideas?
If you need more info let me know.
Thanks Alot,
Chris
Last edited by ...:::ONE:::...; Oct 15th, 2009 at 09:44 PM.
6 Years
-
Oct 15th, 2009, 08:27 AM
#2
Frenzied Member
Re: Finding the Sum of the Data in a Column
-
Oct 15th, 2009, 08:29 AM
#3
Re: Finding the Sum of the Data in a Column
If you mean that you've already populated a DataTable and you want to sum one of its DataColumns then you have two choices:
1. Call Compute on the DataTable:
vb.net Code:
Dim sum As Integer = CInt(table.Compute("SUM(SomeColumn)", Nothing))
2. Use LINQ:
vb.net Code:
Dim sum = table.AsEnumerable().Sum(Function(row) row.Field(Of Integer)("SomeColumn"))
Just note that LINQ requires .NET 3.5.
-
Oct 15th, 2009, 08:32 AM
#4
Re: Finding the Sum of the Data in a Column
Here's a LINQ query-syntax version equivalent to that previous function-syntax version:
vb.net Code:
Dim sum = (From row In table.AsEnumerable() Select row.Field(Of Integer)("SomeSolumn")).Sum()
-
Oct 15th, 2009, 08:33 AM
#5
Thread Starter
Hyperactive Member
Re: Finding the Sum of the Data in a Column
Yeah but I started to wonder if I was actually using it correctly, to I tried to think of another..
this was the original.
Code:
sql = "SELECT sum(dstotal) FROM Table1 WHERE bq1= '" & Label44.Text & "'"
con.Open()
Dim cmd As New OleDb.OleDbCommand(sql, con)
Dim reader As OleDb.OleDbDataReader = cmd.ExecuteReader
reader.Read()
Label44.Text = reader("dstotal")
reader.Close()
con.Close()
I had gotten a circular reference error.
-
Oct 15th, 2009, 08:34 AM
#6
Thread Starter
Hyperactive Member
Re: Finding the Sum of the Data in a Column
thanks jmcilhinney for the code, i'll try it.
-
Oct 15th, 2009, 08:38 AM
#7
Re: Finding the Sum of the Data in a Column
 Originally Posted by ...:::ONE:::...
Yeah but I started to wonder if I was actually using it correctly, to I tried to think of another..
this was the original.
Code:
sql = "SELECT sum(dstotal) FROM Table1 WHERE bq1= '" & Label44.Text & "'"
con.Open()
Dim cmd As New OleDb.OleDbCommand(sql, con)
Dim reader As OleDb.OleDbDataReader = cmd.ExecuteReader
reader.Read()
Label44.Text = reader("dstotal")
reader.Close()
con.Close()
I had gotten a circular reference error.
Follow the CodeBank link in my signature and find my thread on Saving & Retrieving Data to see how to use ADO.NET to execute a scalar query. Also, take note of the other examples that show you how to use parameters to insert variables into SQL statements. Using string concatenation like that is bad.
-
Oct 15th, 2009, 08:40 AM
#8
Frenzied Member
Re: Finding the Sum of the Data in a Column
Your SQL column name return probably doesn't match your reader parameter. Try changing your SQL to this:
sql = "SELECT sum(dstotal) as dstotal FROM Table1 WHERE bq1= '" & Label44.Text & "'"
-
Oct 15th, 2009, 08:52 AM
#9
Re: Finding the Sum of the Data in a Column
 Originally Posted by BrianS
Your SQL column name return probably doesn't match your reader parameter. Try changing your SQL to this:
sql = "SELECT sum(dstotal) as dstotal FROM Table1 WHERE bq1= '" & Label44.Text & "'"
OR even this (as suggested by JM):
Code:
sql = "SELECT sum(dstotal) as dstotal FROM Table1 WHERE bq1= ?Whatever"
Dim cmd As New OleDb.OleDbCommand(sql, con)
cmd.parameters.AddWithValue("?Whatever", Label44.text)
cmd.Prepare
Also, I HIGHLY suggest you come up with more meaning names for your controls. If you really have 44 labels on this form, it's a wonder you can keep them straight.
From my burrow, 2 feet under.
-
Oct 15th, 2009, 08:52 AM
#10
Thread Starter
Hyperactive Member
Re: Finding the Sum of the Data in a Column
 Originally Posted by jmcilhinney
Follow the CodeBank link in my signature and find my thread on Saving & Retrieving Data to see how to use ADO.NET to execute a scalar query. Also, take note of the other examples that show you how to use parameters to insert variables into SQL statements. Using string concatenation like that is bad.
Thanks jmcilhinney, I will take a look at that. I'm not too familiar with the .net structure of things, I'm normally doing interface; but, I'm getting better.
 Originally Posted by BrianS
Your SQL column name return probably doesn't match your reader parameter. Try changing your SQL to this:
sql = "SELECT sum(dstotal) as dstotal FROM Table1 WHERE bq1= '" & Label44.Text & "'"
Actually I appologize, the "Circular Reference Error" was given to me with the "as dstotal" segment inserted. I tried getting rid of it, and I got a new error, haha.. so using the original code I gave you (without the "as dstotal" segment, i got the following error.
"No value given for one or more required parameters."
There are values under the "bq1 column" if that's what it's talking about
Sorry for the confusion.
-
Oct 15th, 2009, 08:55 AM
#11
Thread Starter
Hyperactive Member
Re: Finding the Sum of the Data in a Column
Campion, thanks for the help.. I have a few more things to try.
and about the controls, i try to save time by letting vb give them their defaulted names.. Its not too confusing keeping them that way.
-
Oct 15th, 2009, 08:57 AM
#12
Fanatic Member
Re: Finding the Sum of the Data in a Column
Code:
"No value given for one or more required parameters."
Make sure your column names in the access DB match EXACTLY what you're typing in your query, otherwise you'll receive this error.
and about the controls, i try to save time by letting vb give them their defaulted names.. Its not too confusing keeping them that way.
yah, but dear god I would hate to be the developer who maintained your code at a later point.
-
Oct 15th, 2009, 09:01 AM
#13
Thread Starter
Hyperactive Member
Re: Finding the Sum of the Data in a Column
They are exactly the same. You have no idea how much of a pain this data base has been, ha... For example, I spent hours screwing around with coding to find out that their are certain titles to columns that I cant use, that will cause a syntax , and some other errors.
and Campion, what are u refering to when you are using "?Whatever"
Sorry
-
Oct 15th, 2009, 09:04 AM
#14
Thread Starter
Hyperactive Member
Re: Finding the Sum of the Data in a Column
yah, but dear god I would hate to be the developer who maintained your code at a later point.
hahaha, well I would eventually take care of that... besides that's what the Visual part of VB is for if you need to distinguish controls. Just kidding.
Thanks for your help btw.
-
Oct 15th, 2009, 09:04 AM
#15
Fanatic Member
Re: Finding the Sum of the Data in a Column
?Whatever denotes a paramter where ? represents the parameter and "Whatever" would be the name of the parameter.
-
Oct 15th, 2009, 09:05 AM
#16
Thread Starter
Hyperactive Member
Re: Finding the Sum of the Data in a Column
I see, I'm sorry I've been up for a while now... things are coming slow to me.
Thanks for the help.
-
Oct 15th, 2009, 09:08 AM
#17
Re: Finding the Sum of the Data in a Column
 Originally Posted by ...:::ONE:::...
I see, I'm sorry I've been up for a while now... things are coming slow to me.
Thanks for the help.
Backwoods is correct. One definition of "Whatever" in English is that of a term used to describe something that could have multiple names/meanings/descriptions, etc.
From my burrow, 2 feet under.
-
Oct 15th, 2009, 09:13 AM
#18
Fanatic Member
Re: Finding the Sum of the Data in a Column
well, here's something you can try. Since you're setting a string variable to hold your sql query: run your program, set a breakpoint right after the variable receives the sql string, then go to the immediate window and type in ?sql. Copy and paste the result from the immediate window into your access DB and run the query.
Does it execute in the Access DB?
-
Oct 15th, 2009, 09:16 AM
#19
Re: Finding the Sum of the Data in a Column
 Originally Posted by BackWoodsCoder
Does it execute in the Access DB?
Assuming that he is indeed using Access, then he will need to remove the name of the parameter (not the marker) from the SQL query.
From my burrow, 2 feet under.
-
Oct 15th, 2009, 09:20 AM
#20
Fanatic Member
Re: Finding the Sum of the Data in a Column
That would be true if the parameter was actually there in the sql string result from the immediate window. However, since he's setting a string variable and then setting the string variable as the command text to his sql command object, the parameter value should be populated when he types in ?sql in the immediate window.
Always is for me, it's how I debug parameterized queries when I'm having issues.
Where I'm from we only have one bit of advice for new comers: "If you hear banjos, turn and run".
VS 2008 .NetFW 2.0
-
Oct 15th, 2009, 09:38 AM
#21
Re: Finding the Sum of the Data in a Column
 Originally Posted by BackWoodsCoder
That would be true if the parameter was actually there in the sql string result from the immediate window.
It entirely depends on the connector and the database that you use. Some databases take a parameter name, and others don't like them.
Last edited by Campion; Oct 15th, 2009 at 09:42 AM.
From my burrow, 2 feet under.
-
Oct 15th, 2009, 09:42 AM
#22
Fanatic Member
Re: Finding the Sum of the Data in a Column
It entirely depends on the connector that you use. Some databases take a parameter name, and others don't like them.
I think you're misunderstanding what I'm saying. The immediate window result should not include any parameters, it should include the completed sql query with the parameter being replaced by whatever value the parameter is holding.
Code:
Dim sql as String
Dim sqlCmd as New SqlCommand
sql = "SELECT * FROM SomeWhere WHERE SomeThing = @Param"
sqlcmd.Parameters.AddWithValue("@Param", 1)
sqlcmd.CommandText = sql
Now, if you executed that code and put a breakpoint after the sqlCmd.CommandText line, went to the immediate window and typed in ?sql, the result should look like
Code:
"SELECT * FROM SomeWhere WHERE SomeThing = 1"
Where I'm from we only have one bit of advice for new comers: "If you hear banjos, turn and run".
VS 2008 .NetFW 2.0
-
Oct 15th, 2009, 09:49 AM
#23
Re: Finding the Sum of the Data in a Column
 Originally Posted by BackWoodsCoder
I think you're misunderstanding what I'm saying.
I'm not misunderstanding you. I'm just noting that different database/connector combos may or may not take parameter names in the SQL query. MS SQL Server, MySQL do, while MS SQL Server Lite does not, and SQLite doesn't care either way. Of course, they all use different connectors as well, but could just as easily use the ODBC connector if someone was so inclined.
Access, being a light MS database, AFAIK, does not support named parameters.
From my burrow, 2 feet under.
-
Oct 15th, 2009, 11:24 AM
#24
Fanatic Member
Re: Finding the Sum of the Data in a Column
Sure, it doesn't support Named parameters which is why you use the ?, but you can still name them for readability.
http://www.vbforums.com/showthread.php?t=587547&page=2
It's nothing to do with the OleDbCommand. It's the underlying OLEDB provider that decides what it supports. In this case I assume that it's for clarity. I always use parameters with names when using Access for clarity, even if they aren't used internally.
No, you can use parameters in OLEDB, I do it all the time (as I said I tested his code and it passed with no issues, after I added the semi colon to the connection string!). Unlike SQL though, you must add them in the order that they are found in the code. So if you have @Order and then @Number you must put them in that exact order.
Where I'm from we only have one bit of advice for new comers: "If you hear banjos, turn and run".
VS 2008 .NetFW 2.0
-
Oct 15th, 2009, 11:33 AM
#25
Re: Finding the Sum of the Data in a Column
 Originally Posted by BackWoodsCoder
When you insert the parameters, using X.Parameters, yes. However, I was mentioning in the SQL string itself, not the actual insertion of the parameters.
However, we've veered way off topic.
From my burrow, 2 feet under.
-
Oct 15th, 2009, 11:49 AM
#26
Fanatic Member
Re: Finding the Sum of the Data in a Column
Ah, yes, now i see what you're saying.
So yah, back on track....
Where I'm from we only have one bit of advice for new comers: "If you hear banjos, turn and run".
VS 2008 .NetFW 2.0
-
Oct 15th, 2009, 08:39 PM
#27
Thread Starter
Hyperactive Member
Re: Finding the Sum of the Data in a Column
Ok guys, I appreciate the help.. but I'm lost. Ha.
In stead of listing all my confusing code, I'll write a small example of what I want to do. I'll be straight to the point.
I've added the following references (could use linq, but I hadn't originally)
- System.Data
- System.Data.Xml
Code:
Imports System.Data
Public Class frmSumForm
Dim con As New OleDb.OleDbConnection
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Private Sub ConnectDB()
Dim cb As New OleDb.OleDbCommandBuilder(da)
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Test.mdb"
con.Open()
sql = "SELECT * FROM Table1"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "Table1")
con.Close()
End Sub
Private Sub GetSum()
sql = "SELECT sum(dstotal) FROM Table1 WHERE bq1= '" & lblSumDisplay.Text & "'"
con.Open()
Dim cmd As New OleDb.OleDbCommand(sql, con)
Dim reader As OleDb.OleDbDataReader = cmd.ExecuteReader
reader.Read()
lblSumDisplay.Text = reader("dstotal")
reader.Close()
con.Close()
End Sub
Private Sub frmSumForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ConnectDB()
End Sub
Private Sub btnShowSum_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnShowSum.Click
GetSum()
End Sub
End Class
The error I would receive would be: "No value given for one or more required parameters."
So from what I am understanding at this point is that the way I used my parameters are wrong?
Which would be this part of the sql line?
Code:
'" & lblSumDisplay.Text & "'
I apologize for anymore confusion, and I hope the code above is written right, I kind of wrote it from the top of my head.
Thanks,
Chris
-
Oct 15th, 2009, 08:44 PM
#28
Re: Finding the Sum of the Data in a Column
This is what I said back in post #7:
 Originally Posted by jmcilhinney
Follow the CodeBank link in my signature and find my thread on Saving & Retrieving Data to see how to use ADO.NET to execute a scalar query. Also, take note of the other examples that show you how to use parameters to insert variables into SQL statements. Using string concatenation like that is bad.
I gave you two pieces of advice and you've ignored both. You're still using ExecuteReader instead of ExecuteScalar and you're still using string concatenation to build your SQL statements instead of parameters.
-
Oct 15th, 2009, 08:52 PM
#29
Thread Starter
Hyperactive Member
Re: Finding the Sum of the Data in a Column
jmcilhinney,
I'm sorry I'm from the east coast and I had been up till 10am that morning... I started looking but I had given up when I got lost looking for more info...
I had used your advice, but it didn't work so well.
I had used the code below (because I wasn't using linq) and inserted my information... is this correct?
Code:
Dim sum As Integer = CInt(ds.Tables("Table1").Compute("SUM(bq1)", Nothing))
Is this the only line of code I would need? If so, I had gotten an error.
Thank you, for the help.. my skills seem limited to me.
-Chris
BTW: I am reading the information in your code bank as we speak.
Last edited by ...:::ONE:::...; Oct 15th, 2009 at 08:57 PM.
6 Years
-
Oct 15th, 2009, 09:17 PM
#30
Re: Finding the Sum of the Data in a Column
My original advice was based on the assumption that you already had all the data in a DataTable, in which case querying the database again is pointless. In that case yes, what you have there is basically all you need. If an error occurs and you don't provide us with the error message then there's only so much we can do. We can't read your mind.
If you are going to query the database again then, as I said, the examples in my CodeBank submission will show you how.
-
Oct 15th, 2009, 09:19 PM
#31
Thread Starter
Hyperactive Member
Re: Finding the Sum of the Data in a Column
Ok I found what you were talking about in your code bank
here's the code for the button:
Code:
Using connection As New SqlClient.SqlConnection("UNKNOWN")
Using command As New SqlClient.SqlCommand("SELECT SUM(Quantity) FROM StockItem", connection)
connection.Open()
Dim totalQuantity As Double = CDbl(command.ExecuteScalar())
lilSumDisplay.Text = totalQuantity
End Using
End Using
the "UNKNOWN" part is the connection string I need to use. But I cannot use "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Test.mdb"
How can I connect to the access database?
-
Oct 15th, 2009, 09:22 PM
#32
Thread Starter
Hyperactive Member
Re: Finding the Sum of the Data in a Column
I understand that completely.
When I used the code below:
Code:
Dim sum As Integer = CInt(ds.Tables("Table1").Compute("SUM(bq1)", Nothing))
I get the following error:
"Invalid usage of aggregate function Sum() and Type: String."
The code is reading the table (by inserting an invalid column name, the error basically told me it didn't exist in the table. So by using the correct one it continued to give me the error above.)
-
Oct 15th, 2009, 09:27 PM
#33
Re: Finding the Sum of the Data in a Column
 Originally Posted by ...:::ONE:::...
Ok I found what you were talking about in your code bank
here's the code for the button:
Code:
Using connection As New SqlClient.SqlConnection("UNKNOWN")
Using command As New SqlClient.SqlCommand("SELECT SUM(Quantity) FROM StockItem", connection)
connection.Open()
Dim totalQuantity As Double = CDbl(command.ExecuteScalar())
lilSumDisplay.Text = totalQuantity
End Using
End Using
the "UNKNOWN" part is the connection string I need to use. But I cannot use "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Test.mdb"
How can I connect to the access database?
The answer to that question is in the very first paragraph of that CodeBank thread.
-
Oct 15th, 2009, 09:29 PM
#34
Re: Finding the Sum of the Data in a Column
 Originally Posted by ...:::ONE:::...
I understand that completely.
When I used the code below:
Code:
Dim sum As Integer = CInt(ds.Tables("Table1").Compute("SUM(bq1)", Nothing))
I get the following error:
"Invalid usage of aggregate function Sum() and Type: String."
The code is reading the table (by inserting an invalid column name, the error basically told me it didn't exist in the table. So by using the correct one it continued to give me the error above.)
The error message is telling you that you're trying to sum a column of strings. Of course you can't sum strings. Summing is a mathematical operation so it's performed on numbers. If this column is supposed to contain numbers then is it a text data type and if it doesn't contain all numbers then how can you possibly sum it?
-
Oct 15th, 2009, 09:43 PM
#35
Thread Starter
Hyperactive Member
Re: Finding the Sum of the Data in a Column
jmcilhinney,
I feel retarded. If I hadn't tried to rush, and read through my code more closely. I would have seen that I had..
- To use an oledb connection with an oledb command
- That in my command string I hadn't used "bq1" after SUM
- and that I was getting my information FROM Table1.
Code:
Using connection As New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Documents and Settings\Chris\Desktop\Personal Advisor\Database\TestBase.mdb")
Using command As New OleDb.OleDbCommand("SELECT SUM(bq1) FROM Table1", connection)
connection.Open()
Dim totalQuantity As Double = CDbl(command.ExecuteScalar())
Label44.Text = totalQuantity
End Using
End Using
End Sub
Thanks for your help, I shouldn't have any more problems. Your reference to your code bank was very helpful.
I need to pay more attention ;]
Thanks again,
Chris
-
Oct 15th, 2009, 09:50 PM
#36
Re: [RESOLVED] Finding the Sum of the Data in a Column
All's well what ends well.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|