【发布时间】:2011-02-22 00:50:14
【问题描述】:
正如标题所说,我的目标是在多个列上连接两个表(目标和事务),然后对该连接的结果进行分组,并对两个表中的列值求和。以下查询仅允许访问联接中 FIRST 表中的列!
var actualsVsTargets = (from target in ObjectContext.PipelineTargets
join transaction in ObjectContext.Transactions on
new
{
target.Year,
target.Quarter,
target.StateID,
target.ProductGroup.TeamId
} equals new
{
transaction.Year,
transaction.Quarter,
transaction.StateID,
transaction.Product.ProductGroup.TeamId
}
where target.Year == year && target.ProductGroup.TeamId == teamId
group target by new
{
target.ProductGroupID,
target.StateID,
target.Year
}
into targetGroup
select new
{
// this works fine (accessing target column)
TargetL1 = targetGroup.Sum(target => target.Level1_Target,
// this doesn't work (accessing transaction column)
ActualL1 = targetGroup.Sum(trans => trans.Level1_Total)
}).SingleOrDefault();
如下所示,这在 T-SQL 中实现起来很简单,(大致):
SELECT
targets.Year,
targets.StateID,
SUM(targets.Level1_Target) L1_Target, -- get the sum of targets
SUM(transactions.Level1_Total) L1_Total -- get the sum of transactions
FROM PipelineTargets targets
JOIN Transactions transactions
JOIN Products prods ON
transactions.ProductID = prods.ProductID
ON
targets.Year = transactions.Year and
targets.Quarter = transactions.Quarter and
targets.StateID = transactions.StateID and
prods.ProductGroupID = targets.ProductGroupID
WHERE targets.Year = '2010' and targets.StateID = 1
GROUP BY targets.Year, targets.StateID, targets.ProductGroupID
如何在 LINQ 中执行此操作?
【问题讨论】:
标签: c# linq entity-framework linq-to-entities