Abu bakar
Abu bakar

Reputation: 49

sum up a column in a datatable against an other column in same Datatable

i have a Datatable having following result from database

ID  Name           Class    FeeName       Amount
9   gumman hgjgh    6Th      Fine            0
9   gumman hgjgh    6Th   Tution Fee       3000
9   gumman hgjgh    6Th   Lebority Fee     500
10  AAdil Hussain   5Th     Fine             0
10  AAdil Hussain   5Th   Tution Fee       3000
10  AAdil Hussain   5Th   Lebority Fee      500

i want to sum up amount against each ID so i implement following code

Dim TotalAmount As New DataColumn("TotalAmount", GetType(Double), "Sum(Amount)")
Dtable.Columns.Add(TotalAmount)

But result is following

ID  Name           Class    FeeName       Amount      TotalAmount
9   gumman hgjgh    6Th      Fine            0           7000
9   gumman hgjgh    6Th   Tution Fee       3000          7000
9   gumman hgjgh    6Th   Lebority Fee     500           7000
10  AAdil Hussain   5Th     Fine             0           7000
10  AAdil Hussain   5Th   Tution Fee       3000          7000
10  AAdil Hussain   5Th   Lebority Fee      500          7000

but i want to sum up amount against each Name or ID i have not idea of LINQ

Upvotes: 1

Views: 3152

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460148

I'm afraid a DataTable's Column-Expression cannot SUM(Amount)OVER(PARTITION BY ID).

Here's the LINQ solution:

Dim idGroupAmounts =
    From row In DTable
    Group row By ID = row.Field(Of Int32)("ID") Into IDRowGroup = Group
    Select New With {
        .ID = ID,
        .IDRows = IDRowGroup,
        .IdSum = IDRowGroup.Sum(Function(row) row.Field(Of Double)("Amount"))
    }
For Each idGrpAmount In idGroupAmounts
    Dim id = idGrpAmount.ID
    Dim totalAmount = idGrpAmount.IdSum
    Dim rows = idGrpAmount.IDRows
Next

Upvotes: 1

Related Questions