简体   繁体   English

使用左连接和组的SQL到LINQ

[英]SQL to LINQ with left join and group

I created a worked sql query: 我创建了一个有用的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)  

And I want to rewrite it use 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 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. 我在sql查询中获取日历中的所有行,但在LINQ查询中只有空行(右部分)。 How can I get all calendar's rows in LINQ. 如何在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... 我想把所有日期改为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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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