5

我通常每隔几秒钟通过 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;

谢谢,

4

2 回答 2

5

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

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

于 2013-10-12T06:53:02.573 回答
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
于 2013-10-12T06:52:55.533 回答