将SUM / CASE WHEN / GROUP BY SQL查询转换为LINQ

时间:2014-10-15 20:35:16

标签: c# sql linq

我很难将简单的SQL查询转换为LINQ ...

SELECT Id
  ,Location
  ,SUM( CASE 
        WHEN TransactionType = 'Out' THEN [Quantity] * -1
        ELSE Quantity
        END) AS StockQuantity
FROM Transactions
WHERE Id = 123
GROUP BY Id, Location

这是我最好的错误尝试......

        var result = db.Transactions
            .Where(r => r.Id == 123)
            .GroupBy(r => r.Id, r => r.Location)
            .Select(group => new
            {
                Id = r.Id,
                Location = r.Location,
                Quantity = sum(r.TransactionType == 2 ? r.Quantity * -1 : r.Quantity),

            });

提前致谢

1 个答案:

答案 0 :(得分:0)

您没有使用分组值。您的查询应该是:

var result = db.Transactions
         .Where(r => r.Id == 123)
         .GroupBy(r => new { r.Id, r.Location} )
         .Select(grp => new
         {
             Id = grp.Key.Id,
             Location = grp.Key.Location,
             Quantity = grp.Sum(t=> t.TransactionType == 2 ? t.Quantity * -1 : t.Quantity),

         });

我还会在投影(选择)中使用与group不同的变量名,因为它是一个上下文关键字(带有查询表达式)