SQL COUNT - 具有两个具有不同WHERE子句的COUNT列的输出表

时间:2012-06-11 14:45:38

标签: sql oracle count oracle-apex

我需要在Oracle APEX中生成一个类似于以下示例的报告:

 PROJECT     OPEN_ISSUE_COUNT     CLOSED_ISSUE_COUNT
 W-1         3                    1
 X-2         1                    2
 Y-3         5                    3
 Z-4         2                    1

OPEN_ISSUE_COUNT语句生成CLOSED_ISSUE_COUNTSQL COUNT的位置。被查询的表格如下所示:

 ISSUE_#     ISSUE_STATUS     ASSOCIATED_PROJECT
 1A          OPEN             W-1
 1B          OPEN             W-1
 1C          OPEN             W-1
 2A          CLOSED           W-1
 2B          OPEN             X-2
 2C          CLOSED           X-2
 3A          CLOSED           X-2 
 etc...

因此,在一个查询中,我需要分别计算OPEN_ISSUE_COUNTCLOSED_ISSUE_COUNT分别ISSUS_STATUS = 'OPEN'ISSUS_STATUS = 'CLOSED'以及GROUP BY ASSOCIATED_PROJECT

这有意义吗?显然,我可以轻松地为这两种状态中的一种做到这一点,但是我无法为我在这里描述的内容提出任何可行的解决方案。我在这里和其他地方看过一些东西并没有看到类似的东西。让我知道你们的想法。谢谢!

3 个答案:

答案 0 :(得分:8)

由于count()仅计算非空值,因此应该起作用:

select associated_project as project,
count(case when issue_status='OPEN' then 1 else null end) as open_issue_count,
count(case when issue_status='CLOSED' then 1 else null end) as closed_issue_count
from table
group by associated_project;

当然,这假设issue_status的唯一有效值为'OPEN''CLOSED'。如果不是这种情况 - 并且如果您希望计算其他状态 - 则相应地调整查询。

答案 1 :(得分:4)

另一种方法是使用新的PIVOT功能:

with issue_data as (
  select associated_project as project, issue_status from issues
)
select project, open, closed
  from issue_data
       pivot ( count(*) for issue_status in ('OPEN' as open, 'CLOSED' as closed) )

答案 2 :(得分:1)

select
sum(case when status = 'open' then 1 else 0 end) as open,
sum(case when status = 'closed' then 1 else 0 end) as closed
from table
where  <other restrictions>