[英]SQL to LINQ with left join and group
我创建了一个有用的SQL查询:
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)
我想用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();
我在sql查询中获取日历中的所有行,但在LINQ查询中只有空行(右部分)。 如何在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 o in pp.DefaultIfEmpty()
group pp by DbFunctions.TruncateTime(o.Dt) into g2
select new { date = g2.Key, cnt = g2.Count() }).ToList();
我看到这一个:
{ 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 }
我想把所有日期改为null ...
这个:
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.