【问题标题】:Can I return multiple counters in the same query result (oracle)?我可以在同一个查询结果(oracle)中返回多个计数器吗?
【发布时间】:2016-05-19 12:16:54
【问题描述】:

我想检索与一个值匹配的所有行的计数,同时返回一个不同的计数器,该计数器将根据附加条件计算第一个计数器结果的子集。

例如,我想在一个查询中检索以下查询结果:

Select Count(*), 
from table
where cond1 = '1';

select Count(*)
from table
where cond1 = '1'
And Cond2 ='1';

可以在一个查询中完成吗?

【问题讨论】:

    标签: sql database oracle count


    【解决方案1】:

    您可以像这样使用casesum 来做到这一点:

    select 
       Sum(case when cond1 = 1 then 1 else 0 end) as count1,
       Sum(case when cond1 = 1 and cond2 = 1 then 1 else 0 end) as count2
    from table;
    

    【讨论】:

      【解决方案2】:

      gmiley 的回答很好。

      但是,这个可能会更快一些 - 特别是如果 cond1 被索引!

      select 
         count(*) as count1,
         count(case when cond2 = 1 then 1 end) as count2
      from table
      where cond1 = 1
      

      【讨论】:

        猜你喜欢
        • 2013-02-14
        • 2011-03-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-31
        • 1970-01-01
        • 2014-07-10
        • 2011-08-19
        相关资源
        最近更新 更多