Solved

Datatable grouping

Posted on 2014-12-30
5
179 Views
Last Modified: 2014-12-30
Hi,

I have data table and example of the data could be this

Key    Data
1        5
2        2
1        1
3        4

I need some way of grouping and summing the data so that what I end with is this:

Key    Data
1        6
2        2
3        4

Basically I need the key column to unique and the data column to be the sum of all the common key values

Is this even possible?
0
Comment
Question by:andyw27
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
5 Comments
 
LVL 3

Expert Comment

by:Ali HND
ID: 40523929
SELECT key,  SUM (data)  FROM YourTableName  GROUP BY key;

Open in new window

0
 

Author Comment

by:andyw27
ID: 40523941
Sorry, its a data table, not a SQL table
0
 
LVL 3

Accepted Solution

by:
Ali HND earned 500 total points
ID: 40523970
If your columns was:
Id(key),Value(data)
Imports System.Data
Imports System.Linq

Class Program
	Private Shared Sub Main(args As String())
		Dim table As New DataTable()

		Dim query = From grp In From row In table.AsEnumerable()Group row By row.Field(Of Integer)("Id")Order By grp.KeyNew With { _
			Key .Id = grp.Key, _
			Key .Sum = grp.Sum(Function(r) r.Field(Of Decimal)("Value")) _
		}

		For Each grp As var In query
			Console.WriteLine("{0}" & vbTab & "{1}", grp.Id, grp.Sum)
		Next
	End Sub
End Class

Open in new window

0
 
LVL 70

Expert Comment

by:Qlemo
ID: 40523973
I reckon you need to go thru the table and sum up the values yourself.
0
 

Author Closing Comment

by:andyw27
ID: 40524369
Many Thanks, a particularly useful answer.
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…

752 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question