这是我在SQL中正常工作的SQL查询:
select ld.FolderId, count(ld.LeadId) LeadID, sum(note.noteCount) NoteCount, count(ld.CallResultId) Calls
from LeadsDetails ld
left join
(
select lnh.LeadId, Count(lnh.NoteId) as noteCount
from [dbo].[LeadNoteHistory] lnh
group by lnh.LeadId
)note
on note.LeadId=ld.LeadId
group by ld.FolderId
我试过了 -
var query =
from lead in _context.LeadsDetails
join note in _context.LeadNoteHistories
on lead.LeadId equals note.LeadId into g
from notes in g.DefaultIfEmpty()
group lead by lead.FolderId into grp
select new
{
FolderId = g.FolderId,
LeadID = g.LeadId,
NoteCount = notes.NoteId,
Call = lead.CallResultId
};
无法获得正确的结果。请告诉我我做错了什么。
答案 0 :(得分:0)
稍后您无法在select子句中访问变量'g'。你需要使用变量'grp'。您还需要修改最终组。我尝试修改,看看是否有效:
var query =
from lead in _context.LeadsDetails
join note in _context.LeadNoteHistories
on lead.LeadId equals note.LeadId into g
from notes in g.DefaultIfEmpty()
group new {lead,notes} lead by lead.FolderId into grp
select new
{
FolderId = grp.Key,
LeadID = grp.Count(),
NoteCount = grp.Count(x=>x.notes!=null),
Call = grp.Count()
};
答案 1 :(得分:0)
将SQL转换为LINQ,
将子选择转换为单独的变量
以LINQ子句顺序翻译每个子句,将monadic运算符(DISTINCT
,TOP
等)作为应用于整个LINQ查询的函数。
使用表别名作为范围变量。使用列别名作为匿名类型字段名称。
对多列使用匿名类型(new { }
)
通过使用连接变量并从连接变量执行另一个from
,然后.DefaultIfEmpty()
来模拟左连接。
这是你的SQL翻译:
var rightside = from lnh in dbo.LeadNoteHistory
group lnh by lnh.LeadId into lnhg
select new { LeadId = lnhg.Key, noteCount = lnhg.Count() };
var ans = from ld in dbo.LeadsDetails
join note in rightside on ld.LeadId equals note.LeadId into notej
from note in notej.DefaultIfEmpty()
group new { ld, note } by ld.FolderId into ldnoteg
select new {
FolderId = ldnoteg.Key,
LeadID = ldnoteg.Select(lng => lng.ld.LeadId).Count(),
NoteCount = ldnoteg.Select(lng => lng.note.noteCount).Sum(),
Calls = ldnoteg.Select(lng => lng.ld.CallResultId).Count()
};
我在SQL中保留了LeadID
定义,但这对我来说并不合适。