我正在尝试生成一个查询,以获取每个给定月份内出现日期的条目数。我希望生成的查询的 SQL 形式如下:
SELECT
DatePart(Year, [t1].[StartTime]) as Year,
DatePart(Month, [t1].[StartTime]) as Month,
Count(*) as 'Visits',
Sum([t1].[PageCount]) as 'Total Pageviews'
FROM
[MyDatabase] [t1]
GROUP BY
DatePart(Year, [t1].[StartTime]),
DatePart(Month, [t1].[StartTime])
我尝试了以下 Linq2DB 代码:
var query = from table in dataContext.MyDataContext(tablePath)
group table by new { table.StartTime.Year, table.StartTime.Month} into grp
select new { Month = grp.Key.Month, Year = grp.Key.Year,
TotalVisitors = grp.Count(),
TotalPageviews = grp.Sum(table2 => table2.PageCount) };
但由此生成的 SQL 查询是
-- SqlServer.2008 --
SELECT
[t1].[StartTime],
Count(*) as [c1],
Sum([t1].[PageCount]) as [c2]
FROM
[MyDatabase] [t1]
GROUP BY
DatePart(Year, [t1].[StartTime]),
DatePart(Month, [t1].[StartTime]),
[t1].[StartTime]
为什么是 [t1].[StartTime] 而不是月份或年份?为什么它最后会按额外的 [t1].[StartTime] 分组?如何使用 Linq2DB 生成上面的 SQL 查询?