SQL按类别查找过期产品数和产品总数

时间:2014-06-18 08:43:05

标签: sql oracle

我遇到SQL查询问题。

这是我的产品表:

产品
•id
•姓名
•价格
•过期的 •fk_category

我希望产品数量过期,产品总数按类别分组。

我写下面的查询,我很难完成它:

SELECT COUNT(id) as nb_expired, COUNT (id) as nb_product
FROM product
WHERE expired = 1
GROUP BY fk_category;

你能帮我吗?

2 个答案:

答案 0 :(得分:1)

您可以在case中使用count语句,只对那些已过期的语句使用:

SELECT sum(case when expired = 1 then 1 else 0 end) as nb_expired
,      COUNT (id) as nb_product
FROM   product
GROUP
BY     fk_category

答案 1 :(得分:1)

SELECT fk_category, sum(case when expired = 1 then 1 else 0 end) as expired_count,
COUNT (1) as total 
FROM   product 
GROUP BY     fk_category