LINQ to SQL使用不同的行对多个列进行分组

时间:2010-08-09 05:52:40

标签: c# vb.net linq-to-sql

我有以下表格结构。我想选择不同的CustomerIdCustomerNameTotalCost

这是表结构和列数据类型。

LogId (int)
CustomerId (string)
CustomerName (string)
Cost (int)
  

Logid / CustomerId / CustomerName / Cost

  • 1 2031 John Steward 20
  • 2 2035 Mary Joe 10
  • 3 2034 Robert Tuck 30
  • 4 2031 John Setward 12
  • 5 2036 Luke David 15
  • 6 2033 Kevin Le 14
  • 7 2035 Mary Joe 9
  • 8 2036 Luke David 8
  • 9 2035 Mary Joe 18
  • 10 2037 Jesse Tom 25
  • 11 2032 Antony James 27
  • 12 2033 Kevin Le 26
  

更新1

到目前为止,这是我尝试过的查询:

Dim db As New DemoDataContext()

    Dim query = From log In db.LogRecords _
                 Where log.Cost> 10 _
                 Group log By New With {log.CustomerId, log.CustomerName} Into g() _
                 Select New With {g.CustomerId, g.CustomerName, .Cost = g.Sum(Function(log) log.Cost)}

但是它会使错误消息只能从没有参数的简单或限定名称推断范围变量名。

  

更新2

Dim queryResult = (From log In db.LogRecords _ 
    Group log By log.CustomerId, log.CustomerName Into Cost = Sum(log => log.Cost ) _ 
    Select New With { CustomerId, CustomerName, TotalCost })

For Each q In queryResult

Next

错误:未声明名称'queryResult'。

2 个答案:

答案 0 :(得分:4)

如果我理解你的要求,这样的事情应该在C#中起作用:

var query = from row in dataTable
            group row by new { row.CustomerId, row.CustomerName } into g
            select new
            {
                g.Key.CustomerId,
                g.Key.CustomerName,
                Cost = g.Sum(row => row.Cost)
            };

[编辑]

我想我最初想的为什么它不起作用是错误的。我们的语法错误。

Dim query = From log In db.LogRecords                     _
            Group log By log.CustomerId, log.CustomerName _
                Into Cost = Sum(log => log.Cost)          _
            Select CustomerId, CustomerName, Cost

答案 1 :(得分:3)

只是一个观察。根据Jeff M写的内容并在问题中更新。

 Dim queryResult = (From log In db.LogRecords_
            Where log.Cost > 10 _
            Group log By log.CustomerId, log.CustomerName Into Cost = Sum(log.Cost) _
            Select New With {CustomerId, CustomerName, Cost})