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

use*_*222 5 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';
Run Code Online (Sandbox Code Playgroud)

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

 select type, count(*) from bag group by type;
Run Code Online (Sandbox Code Playgroud)

谢谢,

Rom*_*kar 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
Run Code Online (Sandbox Code Playgroud)

sql fiddle demo