Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 184
  • 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
 
QlemoC++ DeveloperCommented:
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

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

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