views:

38

answers:

1
+1  Q: 

LINQ Query Help!

Can someone hep me converting the following SQL query into LINQ?

select
    convert(varchar(10),date,110) as 'Date',
    max(users) as 'Maximum Number of Users', 
    max(transactions) as 'Maximum Number of Transactions'
from
    stats
where
    datepart(Year, Date) = '2010'
group by
    convert(varchar(10),date,110) 
order by
    convert(varchar(10),date,110)

Thank you in advance!

A: 

It's difficult to tell from the limited information you've provided but this might do the job:

var results = from stat in db.Stats
              group stat by stat.Date.Date into statGroup
              orderby statGroup.Key
              select new
              {
                Date = statGroup.Key,
                MaximumNumberOfUsers = statGroup.Max(c => c.Users),
                MaximumNumberOfTransactions = statGroup.Max(c => c.Transactions)
              };
Daniel Renshaw
DateTime.ToString() isn't supported in L2E. But I don't think it's really needed here anyway.
Craig Stuntz
Thank you so much for your quick response. I ran this query in Linqpad and got this error: Method "System.String ToString(System.String)' has no supported translation to SQL". The Date field has both date and time. I want to groupby only by date,not by time. I am not sure how it can be done.
rk1962
Does the edited version work (use the Date property instead of the ToString method)? Sorry, I have no way to test this right now.
Daniel Renshaw
As Craig said, it worked without ToString. I made a small change in the Select to display Date only: Stats .GroupBy (s => s.Date.Date) .OrderBy (g => g.Key) .Select ( g => new { Date = g.Key.Date.ToShortDateString(), MaximumNumberOfUsers = g.Max (c => c.Users), MaximumNumberOfTransactions = g.Max (c => c.Transactions) } ); THANK YOU Daniel and Craig for your help! I really appreciate it.
rk1962