ef實現一次查詢多個聚合函數的字段

想用ef來寫一個統計字段的語句,以下所示sql

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)這樣一個一個查,沒辦法一次查詢多個聚合函數字段函數

通過個人研究後,我發現能夠曲線救國。spa

dbContext.Table.GroupBy(e => 1).
                Select(g => new
                {
                    price_total:g.Sum(e => e.Price),
                    amount_total:g.Sum(e => e.Amount)
                }).SingleOrDefault();

生成的sql語句以下,還算能夠。code

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)blog

相關文章
相關標籤/搜索