如何编写与此SQL等效的Linq查询

时间:2013-05-23 17:52:41

标签: linq-to-sql sql-to-linq-conversion

我正在试图弄清楚如何编写一个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 

任何帮助都会很棒。

1 个答案:

答案 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)
}