我需要知道如何编写一个LINQ查询,它将给出与此SQL查询相同的结果 :
select sum(col1) as [col1] , sum(col2) as [col2] , sum(col1)/sum(col2) as [col3], col4 as [col4]
from some_table
group by col4
答案 0 :(得分:4)
或者使用Lambda,我假设some_table
是实体或存储库等等。
some_table.GroupBy( row => row.col4).Select( row => new
{
col1 = row.Sum(x => x.col1),
col2 = row.Sum(x => x.col2),
col3 = row.Sum(x => x.col1) / row.Sum(x => x.col2),
col4 = row.Key
});
答案 1 :(得分:3)
完整道具转到Steven获取此答案:https://stackoverflow.com/a/2432348/211627
from row in some_table
group row by row.col4 into g
select new
{
col1 = g.Sum(x => x.col1),
col2 = g.Sum(x => x.col2),
col3 = g.Sum(x => x.col1) / g.Sum(x => x.col2),
col4 = g.Key
};
答案 2 :(得分:2)
这假设您的表是某种实体。这会将它放入Anonymous Type
,但也可用于创建自己类型的对象。
myInitialCollection.GroupBy(x => x.Col4).Select(x =>
new {
col1 = x.Sum(y => y.Col1),
col2 = x.Sum(y => y.Col2),
col3 = (x.Sum(y => y.col1) / x.Sum(y => y.col2)),
col4 = x.Key
});