查询group by和where子句,保留空值

时间:2017-05-03 13:01:57

标签: sql oracle

我有一张下表的表格:

项目,产品,状态

状态可能正在进行,已完成,失败

我想要三个不同的表,列出每个产品的特定状态的项目数。我可以通过计数项目,逐个条款以及状态的条件来实现。得到类似的东西:

对于项目状态=正在进行中:

Product Items
A       10
B       20

和儿子。

但是,如何保留计数(项目)= 0的产品?如果我把条件放在哪里,这些产品就会被过滤掉。

我怎样才能得到像

这样的东西
Product Items
A       10
B       20
C       0
D       0

我正在使用Oracle SQL

这是我使用的查询:

    select product, count(item) from item_main
where status = 'In Progress'
group by product;

2 个答案:

答案 0 :(得分:2)

SELECT Product,
       COUNT( CASE status WHEN 'In Progress' THEN 1 END ) AS Items
FROM   your_table
GROUP BY Product

答案 1 :(得分:0)

SELECT a.product, count(b.product) from 
(select product from item_main group by product) a LEFT JOIN item_main b on a.product = b.product 
where b.status = 'In progress'
相关问题