1

我有一个 SQL:

 SELECT ApplicationNo,COUNT(ApplicationNo) AS CNT, SUM(Amount) as AMNT 
FROM Payments where (TYPE=1 AND Position=1)  and (Date>='2011-01-01')
and (Date<='2012-01-01')
GROUP BY ApplicationNo

有没有办法可以在 Linq 中转换它?

var q = (from payments in context.Payments
                  where payments.Date >= fromdate && payments.Date <= todate
                  group payments by new { payments.ApplicationId } into g
                  select new
                  {
                      applicationId=g.Key,
                      Amount=g.Sum(a=>a.Amount)
                  });

如果我在 Linq 中编写相同的内容,然后最后使用 Group by,我不会得到相同的结果。

4

1 回答 1

1
DateTime fromDate = new DateTime(2011, 1, 1);
DateTime toDate = new DateTime(2011, 1, 1);

var query = 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)
           };

db是您的上下文类。

于 2013-04-23T09:16:53.320 回答