将数据表中的列与同一数据表中的其他列相加

时间:2012-04-27 07:42:28

标签: vb.net

我有一个数据表,其数据库的结果如下:

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

我想总结每个ID的金额,所以我实现以下代码

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

但结果是

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

但我想总结每个姓名或身份证的金额 我不知道LINQ

1 个答案:

答案 0 :(得分:1)

我担心DataTable's Column-Expression无法SUM(Amount)OVER(PARTITION BY ID)

这是LINQ解决方案:

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