如何将具有Group by和Order By的SQL语句转换为vb.net中的LINQ语句

时间:2015-10-22 15:47:52

标签: sql vb.net linq translation

我有以下代码正常工作,但被要求将它合并到一个LINQ语句中:

   Dim AddlOrders = From ords In ctxi.V_TKT_HIST_BVs.AsEnumerable() _
       Select ords Where (ords.CUST_NO = cstno) And (ords.ORIG_STA_ID <> "SWWEB") _
       Order By ords.ORIG_TKT_NO Descending, ords.TKT_DT Descending

    Dim AddlOrds As New Collection(Of V_TKT_HIST_BV)
    Dim o As New V_TKT_HIST_BV
    If (cstno Is Nothing) OrElse (AddlOrders Is Nothing) OrElse (AddlOrders.Count = 0) Then
        AddlOrdersLabel.Text = "You have 0 additional orders."
        AddlOrdersGrid.Visible = False
    Else
        For Each ord In AddlOrders
            If prevord = String.Empty Then
                prevord = ord.ORIG_TKT_NO
                totord = ord.TOT
                o = ord
            ElseIf prevord = ord.ORIG_TKT_NO Then
                totord += ord.TOT
            Else
                o.TOT = totord
                AddlOrds.Add(o)
                prevord = ord.ORIG_TKT_NO
                totord = ord.TOT
                o = ord
            End If
        Next
        If o IsNot Nothing Then
            AddlOrds.Add(o)
        End If

        Dim Addord = From ords In AddlOrds Order By ords.TKT_DT Descending
        AddlOrdersGrid.DataSource = Addord

我尝试过以下语句,但Visual Studio更改了#34;进入os&#34; to&#34;进入os()&#34;并给出一个消息,即在此上下文中无法访问方法os的定义:

Dim orders = From o1 In ctxi.V_TKT_HIST_BVs 
Where o1.CUST_NO = cstno 
Group o1 By o1.TKT_DT, o1.ORIG_TKT_NO, o1.TOT 
Into os() Select ORIG_ORD_NO, total = os.Sum(TOT), 
tdate = os.Last(Function(v) v.TKT_DAT)

SQL的示例如下:

SELECT TOP (200) CUST_NO, EMAIL_ADRS_1, SUM(TOT) AS Expr1, ORIG_TKT_NO, 
       MIN(DISTINCT TKT_DT) AS Expr2
FROM         V_TKT_HIST_BV
GROUP BY CUST_NO, EMAIL_ADRS_1, ORIG_TKT_NO
HAVING      (EMAIL_ADRS_1 LIKE 'name%')
ORDER BY Expr2

有没有人知道为什么会将os改成方法?

1 个答案:

答案 0 :(得分:0)

这将是C#:

AddlOrderGrid.DataSource=ctxi.V_TKT_HIST_BVs
  .Where(t=>t.CUST_NO==cstno)
  .Where(t=>t.ORIG_STA_ID!="SWWEB")
  .GroupBy(t=>t.ORIG_TKT_NO)
  .Select(t=> new {
    CUST_NO=cstno,
    EMAIL_ADRS_1=t.FirstOrDefault().EMAIL_ADRS_1,
    TOT=t.SUM(u=>u.TOT),
    ORIG_TKT_NO=t.Key,
    TKT_DT=t.Min(u=>u.TKT_DT)
  })
  .OrderByDescending(t=>t.TKT_DT);

转换为VB.NET:

Dim Addord = ctxi.V_TKT_HIST_BVs _
 .Where(Function(t) t.CUST_NO = cstno) _
 .Where(Function(t) t.ORIG_STA_ID <> "SWWEB") _
 .GroupBy(Function(t) t.ORIG_TKT_NO) _
 .Select(Function(t) New With { _
    Key .CUST_NO = cstno, _
    Key .EMAIL_ADRS_1 = t.FirstOrDefault().EMAIL_ADRS_1, _
    Key .TOT = t.SUM(Function(u) u.TOT), _
    Key .ORIG_TKT_NO = t.Key, _
    Key .TKT_DT = t.Min(Function(u) u.TKT_DT) _
  }).OrderByDescending(Function(t) t.TKT_DT)
If (Addord.Any()) Then
  AddlOrderGrid.DataSource=Addord
Else
  AddlOrdersLabel.Text = "You have 0 additional orders."
  AddlOrdersGrid.Visible = False
Endif