0

如何在 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。

4

2 回答 2

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
            };
于 2013-01-12T00:44:30.633 回答
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
};
于 2013-01-12T00:51:26.067 回答