SQL to Linq:按ID分组但不能求值

时间:2015-12-03 13:40:25

标签: c# sql linq

我正在搜索相当于此查询的内容:

SELECT Prd.barcode , SumQUA = SUM(AType.unit*MIA.quantity) 
FROM [dbo].[MerchantInventoryActivity] AS MIA
JOIN [dbo].[MerchantInventoryActivityType] AS AType ON (MIA.typeId = AType.id)
JOIN [dbo].[Product] AS Prd ON (MIA.productId = Prd.id)
WHERE MIA.invoiceId =  '123'   
GROUP BY Prd.barcode  

我陷入了SumQUA = SUM(AType.unit * MIA.quantity)。这是我到目前为止所得到的:

(from mia in Entities.MerchantInventoryActivity
join Prd in Entities.Product on mia.productId equals Prd.id
join AType in Entities.MerchantInventoryActivityType on mia.typeId equals AType.id
where mia.invoiceId == invoiceId
group Prd by Prd.barcode into g    
select new 
{
   Barcode = g.Key,
   SumQUA = // ??
}).ToList();

谢谢!

2 个答案:

答案 0 :(得分:1)

您可以先投射到匿名类型然后分组:

(from mia in Entities.MerchantInventoryActivity
    join Prd in Entities.Product on mia.productId equals Prd.id
    join AType in Entities.MerchantInventoryActivityType on mia.typeId equals AType.id
    where mia.invoiceId == invoiceId
    select new { Prd.barcode, AType.unit, MIA.quantity } into temp
    group temp by temp.barcode into g
    select new
    {
        Barcode = g.Key,
        SumQUA = g.Sum(c => c.unit * c.quantity)
    });

答案 1 :(得分:0)

总和

时添加检查空值
(from mia in Entities.MerchantInventoryActivity
        join Prd in Entities.Product on mia.productId equals Prd.id
        join AType in Entities.MerchantInventoryActivityType on mia.typeId equals AType.id
        where mia.invoiceId == invoiceId
        select new { Prd.barcode, AType.unit, MIA.quantity } into temp
        group temp by temp.barcode into g
        select new
        {
            Barcode = g.Key,
            SumQUA = g.Sum(c => c.unit??0 * c.quantity??0)
        });