2

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?

Michael Kossin
  • 342
  • 3
  • 14
  • Thanks @octavioccl, it seems everything works now. Would you mind telling me why it is using the "new" keyword created that extra grouping in the output? – Michael Kossin Mar 14 '17 at 20:10

1 Answers1

0

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

ocuenca
  • 38,548
  • 11
  • 89
  • 102