PostgreSQL多次count()在单个查询中的条件

时间:2013-10-12 06:49:16

标签: sql postgresql

我通常每隔几秒钟通过psycopg2顺序在PostgreSQL 9.1中执行以下SQL查询:

select count(type) from bag where type= 'fruit';
select count(type) from bag where type= 'vegtable';
select count(type) from bag where type= 'other';
select count(type) from bag where type= 'misc';

是否可以在单个选择查询中执行相同的操作,以便即使该计数为零,也可以获得每种类型的计数。如果在给定类型为零时给出零计数,则以下方法可行。

 select type, count(*) from bag group by type;

谢谢,

2 个答案:

答案 0 :(得分:4)

使用派生表作为查询的锚点:

select a.type, count(b.type) 
from (values ('fruit'), ('vegtable'), ('other'), ('misc')) as a(type)
    left outer join bag as b on b.type = a.type
group by a.type

<强> sql fiddle demo

答案 1 :(得分:1)

可以有很多可能的解决方案。一种方法是使用UNION ALL在子查询中生成所有需要的类型,并对LEFT JOIN表执行bag。在这种情况下,您要获取的所有types都将显示在结果列表中,而表bag上的不存在类型将为零计数。这将几乎在所有RDBMS上工作。

SELECT  a.type,
        COUNT(b.type) TotalCount
FROM
        (
            SELECT 'fruit' AS type UNION ALL
            SELECT 'vegtable' AS type UNION ALL
            SELECT 'other' AS type UNION ALL
            SELECT 'misc' AS type 
        ) AS a
        LEFT JOIN bag AS b
            ON a.type = b.type
GROUP   By a.type
相关问题