LinQ查询日期和分组的位置

时间:2013-01-10 16:30:27

标签: sql-server linq

嘿所有我正在努力获得以下查询:

SELECT     Client, Code, COUNT(SessionID) AS Count
FROM       dbo.vw_TrackingAppsCompleteDistinctDate
WHERE      (Date > CONVERT(DATETIME, '2012-12-01 00:00:00', 102) AND Date < CONVERT(DATETIME, '2013-01-01 00:00:00', 102))
GROUP BY   URL, Code, Client
ORDER BY   Client, Code

在ASP.net中转换为LinQ。

到目前为止,我有:

Public Shared Function SelectByID(ByVal start_date As String, ByVal end_date As String) As vw_TrackingAppsCompleteDistinctDate
    Dim db As New MasterDataContext()
    Dim query = From r In db.vw_TrackingAppsCompleteDistinctDates Where r.Date > "1/1/2013"
    Group r By r.URL, r.Code, r.Client Into g
    Select g.All
End Function

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

我正在尝试使用分组进行练习来创建相应的查询。我不是百分百肯定这个linq会得到你希望的结果,因为我无法测试它。

我猜orderby可能不同,因为我不知道SQL是否在分组之前或之后对结果进行排序。

var result = from record in dbo.vw_TrackingAppsCompleteDistinctDate
             where record.Date.CompareTo( new DateTime( 2012, 12, 1, 0, 0, 0 ) ) > 0
             where record.Date.CompareTo( new DateTime( 2013, 1, 1, 0, 0, 0 ) ) < 0
             group record by new { record.URL, record.Code, record.Client } into grp
             orderby grp.Key.Client, grp.Key.Code
             select new 
             {
                 Client = grp.Key.Client,
                 Code = grp.Key.Code,
                 Count = grp.Select( item => item.SessionID ).Count( )
             };

答案 1 :(得分:0)

使用SQL到LinQ转换器:

Dim query = From
              Vw_TrackingAppsCompleteDistinctDates In db.vw_TrackingAppsCompleteDistinctDates
            Where
              Vw_TrackingAppsCompleteDistinctDates.Date > CDate("2012-12-01 00:00:00") 
            And Vw_TrackingAppsCompleteDistinctDates.Date < CDate("2013-01-01 00:00:00")
            Group Vw_TrackingAppsCompleteDistinctDates By
              Vw_TrackingAppsCompleteDistinctDates.URL,
              Vw_TrackingAppsCompleteDistinctDates.Code,
              Vw_TrackingAppsCompleteDistinctDates.Client
            Into g = Group
            Order By Client, Code
            Select
              Client, Code, Count = CType(g.Count(Function(p) p.SessionID <> Nothing), Int64?)