Sql转换为Linq - Left Join,Group,Min和Sum

时间:2012-03-07 16:51:19

标签: sql sql-server linq

我有这个简单的sql,完全符合我的需要......

SELECT MIN(pb.Id) AS Id, MIN(pb.Quantity) AS Requested, SUM(pbi.Quantity) AS Total
FROM PickBatchItems AS pb
LEFT JOIN PickBatchItemLocations AS pbi ON pb.Id = pbi.PickBatchItemId
GROUP BY pb.Id

结果......

Id, Requested, Total
 1    100       NULL
 2    200       165
 3    200       NULL 

这正是我想要的,但我需要这个在Linq。

到目前为止,我有......

var pick = (from pb in db.PickItems
           join pbi in db.PickItemLocations on pb.Id equals pbi.PickBatchItemId into TempJoin
           from resList in TempJoin.DefaultIfEmpty()
           where pb.Id == iPickItemId
           group resList by pb.Id into g
           select new
           {
               Id = g.Key,
               RequestedQuantity = g.Min(???????????????????????),
               SentQuantity = g.Sum(a => a.Quantity == null ? 0 : a.Quantity),
           }).FirstOrDefault();

如何获得 RequestedQuantity

更新

感谢'大卫B'我有答案:

var pick = (from pb in db.PickBatchItems
            join pbi in db.PickBatchItemLocations on pb.Id equals pbi.PickBatchItemId into TempJoin
            from resList in TempJoin.DefaultIfEmpty()
            where pb.Id == iPickItemId
            group new { PickItem = pb, PickItemLocation = resList } by pb.Id into g
            select new
            {
                Id = g.Key,
                RequestedQuantity = g.Min(a => a.PickItem.Quantity),
                SentQuantity = g.Sum(a => a.PickItemLocation.Quantity == null ? 0 : a.PickItemLocation.Quantity),
            }).FirstOrDefault();

即使PickBatchItemLocations表为空,这也会加入并返回我的两个表。

1 个答案:

答案 0 :(得分:4)

假设PickItems.Id是主键,似乎加入是不需要旅行的道路的第一步。

from pb in db.PickItems
where pb.Id = iPickItemId //this wasn't in the original sql
select new
{
  Id = pb.Id,
  RequestedQuantity = pb.Quantity,
  SentQuantity = pb.PickItemLocations.Sum(pbi => pbi.Quantity)
};

如果您仍想走很长的路,请执行以下操作:

group new {PickItem = pb, PickItemLocation = resList } by pb.Id into g
select new
{
  Id = g.Key,
  RequestedQuantity = g.Min(x => x.PickItem.Quantity),
  SentQuantity = g.Sum(x => x.PickItemLocation.Quantity ?? 0)
}