Linq to Entities Group By

时间:2012-11-21 19:31:15

标签: sql linq group-by

我编写了以下MS SQL Server查询,但在使用linq to entity语句时遇到问题:

目标是从过去7天内的数据库中检索潜在客户,然后按周分组并计算每天的潜在客户数

SELECT      DATEPART(day, DateCreated) AS Day, LEFT(DATENAME(dw, DateCreated), 3) AS DayOfWeek, COUNT(*) AS Count
FROM         dbo.[File]
WHERE     (DateCreated > GETDATE() - 7)
GROUP BY DATEPART(day, DateCreated), DATENAME(dw, DateCreated)
ORDER BY Day, DATENAME(dw, DateCreated)

示例结果如下:

以下是包含示例结果的链接:link

如何使用linq向实体编写此示例的任何帮助将非常感激。 Vb(首选)或c#?

谢谢

2 个答案:

答案 0 :(得分:2)

试试这个

var query =
    from f in File
    where f.DateCreated > DateTime.Now.AddDays(-7)
    group f by new { Day = f.DateCreated.Day, DayOfWeek = f.DateCreated.DayOfWeek } into g
    select new
    {
        Day = g.Key.Day,
        DayOfWeek = g.Key.DayOfWeek.ToString().Substring(0, 3),
        Count = g.Count()
    };

如果您需要特定于文化的名称,可以使用Date.ToString("dddd", System.Globalization.CultureInfo.CreateSpecificCulture("en-US"))

var query =
    from f in File
    where f.DateCreated > DateTime.Now.AddDays(-7)
    group f by new { Day = f.DateCreated.Day, DayOfWeek = f.DateCreated.ToString("dddd", System.Globalization.CultureInfo.CreateSpecificCulture("en-US")) } into g
    select new
    {
        Day = g.Key.Day,
        DayOfWeek = g.Key.DayOfWeek.Substring(0, 3),
        Count = g.Count()
    };

<强>更新 好吧,我不是VB专家,但对于VB你可以试试这样的东西

    Dim query =
    From f In File
    Where f.DateCreated > DateTime.Now.AddDays(-7)
    Group f By Day = f.DateCreated.Day, DayOfWeek = f.DateCreated.DayOfWeek.ToString().Substring(0, 3)
    Into Group, Count = Count()

答案 1 :(得分:1)

最好不要在Linq-to-SQL中按天和星期分组,而只是按日期分组,然后在查询之外提取日期部分(因为稍后处理日期不会影响查询性能):

var query = 
    (from f in Files 
        where EntityFunctions.AddDays(f.DateCreated, 7) >= DateTime.Today()
        group f by EntityFunctions.TruncateTime(f.DateCreated) into g
        select new { DateCreated = g.Key, Count = g.Count() })
    .ToList()  // materialize to switch from Linq-to-SQL to Linq-to-Objects
    .Select( g => new { 
                       Day = g.DateCreated.Day,, 
                       DayOfWeek = g.DateCreated.ToString("ddd"),
                       Count = g.Count
                       });