使用Entity Framework将聚合函数组合在多个表上

时间:2016-05-05 14:29:48

标签: c# entity-framework linq

我目前以这种方式得到2个聚合函数结果:

var fooCount = ctx.Foo.Count();
var barCount = ctx.Bar.Count();

这会产生2个不同的SQL查询。我正在寻找一种方法将这些组合成一个查询。

在纯SQL中,我可以这样组合这两个查询:

SELECT 
  (SELECT COUNT(*) FROM Foo) AS FooCount,
  (SELECT COUNT(*) FROM Bar) AS BarCount

我们如何使用Entity Framework执行此操作?我找到的只是multiple aggregate function in the same table。但就我而言,它是不同的表格。

我试过这样的事情没有成功:

var query = from together in (new
{
    FooCount = db.Foo.Count(),
    BarCount = db.Bar.Count()
}) select together; //<-- visual studio let me not write "select together;"

1 个答案:

答案 0 :(得分:2)

我认为你想要的是这样的。基本上按常量分组允许您将计数聚合作为df = pd.concat([df]*1000).reset_index(drop=True) In [787]: %timeit df[df.filter(like='var1_').apply(lambda r: (r != 0).sum() > 1, axis=1)] 1 loops, best of 3: 746 ms per loop In [788]: %timeit df[(df.ix[:,'Var1_Belgium':] != 0).sum(axis=1) > 1] The slowest run took 4.49 times longer than the fastest. This could mean that an intermediate result is being cached 1000 loops, best of 3: 1.39 ms per loop In [789]: %timeit df[(df.filter(like='var1') != 0).sum(1) > 1] The slowest run took 4.64 times longer than the fastest. This could mean that an intermediate result is being cached 1000 loops, best of 3: 1.48 ms per loop In [790]: %timeit df[(df.iloc[:,1:] != 0).sum(axis=1) > 1] 1000 loops, best of 3: 1.34 ms per loop 进行,然后您可以交叉连接它们。但我不知道这是值得的。基本上你的交易可读性可能会提高一些性能。

IQueryable<int>