Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting SQL containing top, count, group and order to LINQ (2 Entities)

Tags:

sql

linq

Some LINQ queries still puzzle me.

for a table 'Hits' containing two columns, 'Page' and 'Date', I want to find the most Pages with the most rows in a defined slice of time.

In SQL I would use this:

SELECT TOP 10
      [Page]
      ,COUNT([Page]) as Number
FROM dbo.[Hits]
WHERE [Date] >= CONVERT(datetime,'14 Jan 2009')
AND [Date] < CONVERT(datetime,'15 Jan 2009')
Group BY [Page]
Order by Number DESC

In LINQ I got no idea how to approach this, can anyone help me here? I tried to convert it using linqer, but it just shows an error for this expression.

like image 746
Sam Avatar asked Mar 03 '09 12:03

Sam


2 Answers

Something like this should work:

(from p in DataContext.Hits
where (p.Date >= minDate) && (p.Date < maxDate)
group p by p.Page into g
select new { Page = g.Key, Number = g.Count() }).OrderByDescending(x => x.Number).Take(10);
like image 140
veggerby Avatar answered Nov 15 '22 09:11

veggerby


var top10hits = objectContext.Hits
  .Where(h => minDate <= h.Date && h.Date < maxDate)
  .GroupBy(h => h.Page)
  .Select(g => new { Page = g.Key, Number = g.Count() })
  .OrderByDescending(x => x.Number)
  .Take(10);
like image 21
Amy B Avatar answered Nov 15 '22 10:11

Amy B