当Sum(x)>时GroupBy +情况0然后Sum(x)否则为0

时间:2013-01-12 00:38:44

标签: linq group-by sum case-when

如何在LINQ中复制以下内容

SELECT KEY_COLUMN,
        CASE WHEN SUM(COLUMN2) < 0 THEN SUM(COLUMN2) ELSE 0 END AS NewColumn
FROM TABLE
GROUP BY KEY_COLUMN

到现在为止我可以提出以下

var result = from a in source
               group a by a.Key_Column
                   into g
                   select new
                   {
                       Key_Column = g.Key,
                       NewColumn = g.Where(item => item.Column2 < 0)
                                    .Sum(item => item.Column2)
};

上面的代码在确定它是否为负数之前并没有真正总结Column2。

2 个答案:

答案 0 :(得分:2)

var query = from a in db.Table
            group a by a.Key_Column into g
            let sum = g.Sum(item => item.Column2)
            select new {
               Key_Column = g.Key,
               NewColumn = sum < 0 ? sum : 0
            };

答案 1 :(得分:0)

这不是一样的吗?

var query = from r in db.Table
  group r by r.KEY_COLUMN into g
  select new {
    KEY_COLUMN = g.Key,
    NewColumn = g.Sum(x => x.COLUMN2) < 0 ? g.Sum(x => x.COLUMN2) : 0
};