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

6

我通常通过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个回答

6

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

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演示


我在最后加了一个按类型排序的命令,正是我想要的。谢谢。 - user2695222

1

有很多可能的解决方案。其中一种方法是通过使用UNION ALL在子查询中生成所有所需类型,并针对bag表执行LEFT JOIN。在这种情况下,您想要获取的所有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

感谢您的帮助。谢谢。 - user2695222

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接