我试图在C#中使用Linq2Db生成一个sql查询。我想要生成的查询是:
SELECT
cast([t1].[StartTime] as date) as [StartTime1],
Count(*) as [WebpageVisits],
Sum([t1].[PageCount]) as [SumOfViewsOfPages]
FROM
[myserver].[dbo].[TrackData] [t1]
GROUP BY cast([t1].[StartTime] as date)
我试图使用的Linq代码是:
var query = from table in dataContext.TrackData(tablePath)
group table by new { table.StartTime.Date } into grp
select new { day = grp.Key.Date, numVisitors = grp.Count(), totalPageViews = grp.Sum(table2 => table2.PageCount)};
返回的查询是
-- SqlServer.2008
SELECT
[t1].[StartTime],
Count(*) as [c1],
Sum([t1].[PageCount]) as [c2]
FROM
[myserver].[dbo].[TrackData] [t1]
GROUP BY
Convert(Date, [t1].[StartTime]),
[t1].[StartTime]
为什么会出现额外的[t1]。[StartTime]?这导致结果不会根据日期进行分组。如何生成我尝试使用Linq生成的SQL查询?
答案 0 :(得分:0)
尝试分组删除匿名类型:
group table by table.StartTime.Date into grp
如果要按多列分组,则应使用匿名类型。我试过你在LinqPad中查询而我无法模拟相同的行为,但这是你应该遵循的原则