简体   繁体   中英

SQL to LINQ with left join and group

I created a worked sql query:

select CONVERT(date, C.tDate) as dt, count(O.Id) as cnt  from [Calendar] C
left outer join [Order] O
on C.tDate = CONVERT(date, O.Dt)
group by CONVERT(date, C.tDate)
order by CONVERT(date, C.tDate)  

And I want to rewrite it use LINQ:

var res = (from c in db.Calendars
join o in db.Orders on c.tDate equals DbFunctions.TruncateTime(o.Dt.Value) into pp
from pl in pp.DefaultIfEmpty()
group c by DbFunctions.TruncateTime(pl.Dt.Value) into g
orderby g.FirstOrDefault().tDate
select new { date = g.FirstOrDefault().tDate, cnt = g.Count() }).ToList();

I get all rows from calendar in sql query, but only not null rows (right part) in LINQ query. How can I get all calendar's rows in LINQ.

Added: Then I try:

var res = (from c in db.Calendars
join o in db.Orders on c.tDate equals DbFunctions.TruncateTime(o.Dt.Value) into pp
from o in pp.DefaultIfEmpty()
group pp by DbFunctions.TruncateTime(o.Dt) into g2
select new { date = g2.Key, cnt = g2.Count() }).ToList();

And I see this one:

{ date = null, cnt = 1062 } 
{ date = {25.01.2019}, cnt = 4 }
{ date = {26.01.2019}, cnt = 7 }
{ date = {27.01.2019}, cnt = 16 }
{ date = {28.01.2019}, cnt = 5 }

I want to get all dates instead null...

This one:

var res = (from c in db.Calendars
join o in db.Orders on c.tDate equals DbFunctions.TruncateTime(o.Dt.Value) into pp
from o in pp.DefaultIfEmpty()
group pp by DbFunctions.TruncateTime(c.tDate) into g2
orderby g2.Key
select new { date = g2.Key, cnt = g2.FirstOrDefault().Count() }).ToList();

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM