按linq查询分组加入和分组

时间:2014-06-11 12:46:43

标签: vb.net linq

我是LINQ的新手,我想创建一个简单的查询。下面是我的SQL,我想将其转换为vb.net中的LINQ查询。

 Dim strQuery As String = "SELECT h.head_name as head, sum(d.debit_amount) as debit, sum  (d.credit_amount) as credit " & _
                                    " FROM ((daybook AS d) LEFT JOIN heads AS h ON d.head_id = h.head_id) " & _
                                    " where d.entry_date >= #" & CDate(dtFrom.Value) & "# And d.entry_date <= #" & CDate(dtTo.Value) & "# " & _
                                    " and d.head_id <> 21 " & _
                                    " group by h.head_name " & _
                                    " ORDER BY h.head_name"

我所做的是:

Dim query = From d In gbl_dsCommonDaybook.Tables(0) _
                      Where CDate(d!entry_date) >= CDate(dtFrom.Value) And CDate(d!entry_date) <= CDate(dtTo.Value) _
                      And CInt(d!head_id) <> HeadID.CashInHand _
                      Group Join h In gbl_dsHeads.Tables(0) On d!head_id Equals h!head_id Into grp = Group _
                      From g In grp.DefaultIfEmpty _
                      Group g By g!head_name Into gh = Group _
                      Order By head_name Ascending _
                      Select New With _
                   {
                       .head = head_name.ToString, _
                       .debit = gh.Sum(Function(s) CSng((s!debit_amount))), _
                       .credit = gh.Sum(Function(s) CSng(s!credit_amount)) _
                   }

执行查询时,未将对象引用的错误设置为对象的实例。 我努力解决它但无济于事。请帮忙。

0 个答案:

没有答案