I am trying to generate an sql query using Linq2Db in C#. The query I want to generate is this:
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)
The Linq code I am trying to use is this:
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)};
The query returned is
-- 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]
Why is that extra [t1].[StartTime] appearing there? This is causing the result to NOT be grouped based on date. How do I generate the SQL query I am trying to generate using Linq?
Try to group removing the anonymous type:
group table by table.StartTime.Date into grp
You should use an anonymous type in case you want to group by more than one column. I tried you query in LinqPad and I couldn't simulate the same behavior, but that is the principle you should follow in the future
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.