想用ef来写一个统计字段的语句,如下所示
select sum(price) as price_total, sum(amount) as amount_total from table1
发现似乎实现不了,ef只能 dbContext.Table.Sum(e=>e.price);dbContext.Table.Sum(e=>e.amount)这样一个一个查,没办法一次查询多个聚合函数字段
经过我的研究后,我发现可以曲线救国。
dbContext.Table.GroupBy(e => 1). Select(g => new { price_total:g.Sum(e => e.Price), amount_total:g.Sum(e => e.Amount) }).SingleOrDefault();
生成的sql语句如下,还算可以。
SELECT SUM(`t`.`amount`) AS `remain`, SUM(`t`.`price`) AS `price` FROM ( SELECT `e`.*, 1 AS `Key` FROM `it_asset` AS `e` ) AS `t` GROUP BY `t`.`Key` LIMIT 2
还有一个需要注意的点,如果你需要Sum(amount1-amount2)这样的话,在GroupBy里面千万不能这样写 Sum(e=>e.amount1-e.amount2),得这样写Sum(e=>amount1)-Sum(e=>e.amount2)