微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在Linq中加入子查询结果

如何解决在Linq中加入子查询结果

是的,您可以加入子查询。像这样:

var query = from f in db.ApplicationFees
            join sub in (from p in db.Payments
                         where p.Type == 1 && p.Position == 1 && 
                               p.Date >= fromDate && p.Date <= toDate
                         group p by p.ApplicationNo into g
                         select new {
                              ApplicationNo = g.Key,
                              CNT = g.Count(),
                              AMNT = g.Sum(x => x.Amount)
                         }) 
           on f.ApplicationNo equals sub.ApplicationNo into feePayments
           select new { Fee = f, Payments = feePayments };

但是在单个查询中编写它不是很容易维护。考虑从单独 定义的查询组成查询

var payments = from p in db.Payments
               where p.Type == 1 && p.Position == 1 && 
               p.Date >= fromDate && p.Date <= toDate
               group p by p.ApplicationNo into g
               select new {
                    ApplicationNo = g.Key,
                    CNT = g.Count(),
                    AMNT = g.Sum(x => x.Amount)
              };

var query = from f in db.ApplicationFees
            join p in payments 
               on f.ApplicationNo equals p.ApplicationNo into feePayments
            select new { Fee = f, Payments = feePayments };

解决方法

我对我的另一个疑问是:是否有一种方法可以使用一个查询的结果,然后像在SQL中一样进一步将其联接:

SELECT Applications.*,ApplicationFees.ApplicationNo,ApplicationFees.AccountFundDate1,ApplicationFees.AccountFundDate2,ApplicationFees.AccountFundDate3,ApplicationFees.AccountCloseDate1,ApplicationFees.AccountCloseDate2,ApplicationFees.AccountCloseDate3,isnull(SUBQRY11.AMNT,0) as SCMSFEE1R,isnull(SUBQRY12.AMNT,0) as SCMSFEE2R,Left Join 
(
SELECT ApplicationNo,COUNT(ApplicationNo) AS CNT,SUM(Amount) as AMNT 
FROM Payments where (FEETYPE=1 AND FeePosition=1)  and (FeeDate>='2011-01-01')
and (FeeDate<='2012-01-01')
GROUP BY ApplicationNo
)SUBQRY11
ON ApplicationFees.ApplicationNo= SUBQRY11.ApplicationNo 
Left Join 
(
SELECT ApplicationNo,COUNT(ApplicationNo) AS CNT2,SUM(Amount) as AMNT

FROM Payments where (FEETYPE=1 AND FeePosition=2) and (FeeDate>='2011-01-01') 
 and (FeeDate<='2012-01-01')
GROUP BY ApplicationNo )SUBQRY12 ON ApplicationFees.ApplicationNo=SUBQRY12.ApplicationNo

我想在查询的foreach中避免同样的事情,因为这将非常耗时。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。