entity-framework - 如何在 LINQ 中使用聚合函数?
问题描述
我可以在 SQL 中很容易地做到这一点,但我无法将其转换为 LINQ。
SQL:
SELECT EmployeeId
,YEAR(DistributionDate) AS DistributionYear
,SUM(SalesLocal * FX.ExchangeRate) AS TotalDistributions
FROM Distributions AS DD INNER JOIN FiscalPeriod AS FP ON DD.DistributionDate BETWEEN FP.StartDate AND FP.EndDate
INNER JOIN FXRates AS FX ON FP.FiscalPeriodId = FX.FiscalPeriodId AND FX.FromCurrencyId = DD.CurrencyId AND FX.ToCurrencyId = 'USD'
GROUP BY EmployeeId, YEAR(DistributionDate)
ORDER BY EmployeeId, DistributionYear
这是我失败的翻译尝试:
var pointList = (from dd in db.Distributions
join e in db.Employee on dd.EmployeeId equals e.EmployeeId
join fp in db.FiscalPeriod.Where(p => dd.DistributionDate >= p.StartDate && dd.DistributionDate <= p.EndDate)
join fx in db.Fxrates on (fp.FiscalPeriodId equals fx.FiscalPeriodId) && (fx.FromCurrencyId equals dd.CurrencyId) && (fx.ToCurrencyId equals "USD")
group by dd.EmployeeId && dd.DistributionDate.Year
select new Point<int, decimal?>
{
X = dd.DistributionDate.Year,
Y = dd.Sum(dd.SalesLocal * fx.ExchangeRate)
}).ToList();
Visual Studio 首先抱怨dd
未声明的内容,然后在到达连接到Fxrates
.
解决方案
我认为这可能接近你想要的:
var pointList = (from dd in db.Distributions
join e in db.Employee on dd.EmployeeId equals e.EmployeeId
from fp in db.FiscalPeriod.Where(p => dd.DistributionDate >= p.StartDate && dd.DistributionDate <= p.EndDate)
from fx in db.Fxrates.Where(fx2 => fp.FiscalPeriodId == fx2.FiscalPeriodId && fx2.FromCurrencyId == dd.CurrencyId && fx2.ToCurrencyId == "USD")
group new { dd, fx } by new { dd.EmployeeId, dd.DistributionDate.Year } into distGroup
select new
{
X = distGroup.Key.Year,
Y = distGroup.Sum(d => d.dd.SalesLocal * d.fx.ExchangeRate)
}).ToList();
推荐阅读
- javascript - 列表倒序
- node.js - 如何使用 axios 在 react.js 端处理后端动态分配的端口?
- python - PyQT5:单击按钮时获取文件名,获取attributeError
- python-3.x - 如何修复失败的条件语句
- node.js - 提供 Firebase 功能总是说端口未打开
- python - Boto3 S3 资源卡在“Object.get”方法上
- list - 列出包“MoveToFront”对我不起作用
- ostream - boost.log和ostream如何配合?
- r - 是否有一个 R 函数可以在 for 循环中查找列的类别
- mysql - 如何将值显示为字符串,从数据库中得到什么?