SubSelects in LINQ

What a challenge I was facing trying to figure out how to solve this problem in LINQ.. but i did it .. and am sharing.

SQL query:

Select Distinct 
o.ConceptCode,
u.firstname,
u.lastname,
(select count(*) from callLead where calldate ='2014-09-02'  and conceptcode=O.conceptcode and userid=O.userid) 'DailyTotal'
,(select count(*) from callLead where calldate between '2014-09-01'  and '2014-09-05' and conceptcode=O.conceptcode and userid=O.userid) 'WTD'
,(select count(*) from callLead where datepart(m,calldate)=9 and conceptcode=O.conceptcode and userid=O.userid) 'MTD'
,(select count(*) from callLead where datepart(yyyy,calldate)=2014 and conceptcode=O.conceptcode and userid=O.userid) 'YTD'
from callLead Ojoin users u on o.userid=u.userid

The LINQ Conversion:

The LINQ version is much prettier actually
 var rptSummary = (from e in SalesEntities.CallLeads
                            join j in SalesEntities.Users on e.UserID equals j.UserID
                              group e by new{  e.ConceptCode,e.UserID,j.FirstName,j.LastName}  into g
                         
                           select new
                             {
                                 Concept = g.Key.ConceptCode,
                                 UserID = g.Key.UserID,
                                 FirstName = g.Key.FirstName,
                                 LastName = g.Key.LastName,
                                 DailyTotal = g.Count(e=>e.CallDate == datesent),
                                 WTD = g.Count(e => e.CallDate >= firstdayofweek && e.CallDate <= lastdayofweek),
                                 MTD = g.Count(e => e.CallDate.Month == mo),
                                 YTD = g.Count(e => e.CallDate.Year == yr)

                             }).OrderByDescending(e => e.Concept);

Comments

Popular posts from this blog

Linq Exclude from separate list

Sorting Ascending and Descending

Linq Query Syntax vs Method Syntax