1

我编写了以下 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 to 实体编写此示例的帮助将不胜感激。Vb(首选)还是 c#?

谢谢

4

2 回答 2

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()
于 2012-11-21T19:59:57.567 回答
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
                       });
于 2012-11-21T20:01:50.993 回答