Quantcast
Channel: VBForums - Visual Basic .NET
Viewing all articles
Browse latest Browse all 27554

VS 2012 DataTable: How to get the sum of Column for each distinct data?

$
0
0
Good day. Here is my problem.

I have a datatable that is filled in with user input.


Code:

Dim dt as datatable
dt.columns.add("Id",gettype(Integer))
dt.columns.add("Amount",gettype(Double))

Now here is sample user input:

Code:

dt.rows.add(1,3)
dt.rows.add(2,20)
dt.rows.add(1,3)
dt.rows.add(3,30)
dt.rows.add(1,4)

I want to get the total amount for each ID, Can you help me how to get my desired output?

Id: 1
Total Amount: 10

Id: 2
Total Amount : 20

Id: 3
Total Amount : 30

In which i will put in a new Datatable like this.

Code:

Dim dtnew as datatable
dtnew.columns.add("Id",gettype(Integer))
dtnew.columns.add("Total",gettype(Double))

dtnew.rows.add(1,10)
dtnew.rows.add(2,20)
dtnew.rows.add(3,30)

As of now, all i know is how to compute amount for each id but not assign them to their respective Id.

Im doing this.

Code:

For i = 0 to dt.rows.count - 1
Dim total() as integer
total() = dt.Compute("SUM(Amount), "Id = '" & dt.rows(i)(0) & "'")
Next

Thank you. Please help. :)

Viewing all articles
Browse latest Browse all 27554

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>