我正在试图弄清楚如何编写一个linq查询,该查询将返回与下面的sql查询相同的结果。我遇到的问题与主查询的选择列表中包含的两个选择计数查询有关。我需要从去年的PaymentHistory
表中获取两种不同类型记录的计数。是否可以使用linq编写相当的内容?最好使用lambda语法。
select ieinum, serviceaddrkey,
(select count(*) from PaymentHistory where serviceaddrid = serviceaddrkey
and PostDate >= DateAdd(year, -1 , GetDate())
and SetID = 100) as ReturnedFees,
(select count(*) from PaymentHistory where serviceaddrid = serviceaddrkey
and PostDate >= DateAdd(year, -1 , GetDate())
and SetID = 101) as CorrectedReturnedFees
from Serviceaddr
任何帮助都会很棒。
答案 0 :(得分:0)
也许是这样的:
from s in Serviceaddr
let ph = PaymentHistory.Where(p => s.serviceaddrkey == p.serviceaddrkey &&
p.PostDate >= DateTime.Now.AddYears(-1))
select new
{
s.ieinum,
s.serviceaddrkey,
ReturnedFees = ph.Count(p => p.SetID == 100),
CorrectedReturnedFees = ph.Count(p => p.SetID == 101)
}