Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 188
  • Last Modified:

Datatable grouping

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
andyw27
Asked:
andyw27
  • 2
  • 2
1 Solution
 
Ali HNDCommented:
SELECT key,  SUM (data)  FROM YourTableName  GROUP BY key;

Open in new window

0
 
andyw27Author Commented:
Sorry, its a data table, not a SQL table
0
 
Ali HNDCommented:
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
 
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
I reckon you need to go thru the table and sum up the values yourself.
0
 
andyw27Author Commented:
Many Thanks, a particularly useful answer.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now