Linq to Sql查询具有多个聚合 [英] Linq to Sql query with multiple aggregations

查看:59
本文介绍了Linq to Sql查询具有多个聚合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个简单的模式,例如PurchaseOrders {OrderId,Total,LineItemCount},我想为一些简单的统计信息生成一个简单的查询,如下所示:

Given a simple schema e.g. PurchaseOrders { OrderId, Total, LineItemCount }, I want to generate a simple query for some simple stats like below:

select sum(lineitemcount) as totalitems, sum(total) as totalsales
from purchaseorders

但是,在Linq to Sql中,我正在努力将其纳入一个查询中.

However in Linq to Sql I am struggling to get this into one query.

此刻我有这个:

decimal totalSales = PurchaseOrders.Sum(po => po.Total)
decimal totalItems = PurchaseOrders.Sum(po => po.LineItemcount)

有没有一种方法可以做到这一点?

Is there a way to do this as one query?

推荐答案

最近我能解决的是给它一个假的group-by子句.它可以正常工作,并按您的期望进行输出,但是生成的SQL实际上最终传入了参数"1"并对其进行分组,这有点次优.这是我所学到的语法:

Closest I can work out is to give it a fake group-by clause. It works, and outputs as you'd expect, but the generated SQL actually winds up passing in a parameter of "1" and grouping on it which is a tad suboptimal. Here's the syntax for what I've got though:

PurchaseOrders
    .GroupBy(po => 1)
    .Select(pogroup => new {
           TotalSales = pogroup.Sum(po => po.Total),
           TotalItems = pogroup.Sum(po => po.LineItemCount)
        });

这篇关于Linq to Sql查询具有多个聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆