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
};
GroupBy + Case When Sum(x) > 0 then Sum(x) else 0
Pregunta
How can I replicate following in LINQ
SELECT KEY_COLUMN,
CASE WHEN SUM(COLUMN2) < 0 THEN SUM(COLUMN2) ELSE 0 END AS NewColumn
FROM TABLE
GROUP BY KEY_COLUMN
till now I could come up with following
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)
};
above code is not really summing up the Column2 before deciding if it's a negative number or not.
Solución
Otros consejos
isn't this the same ?
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
};
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow