我通常每隔几秒通过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;
谢谢,
使用派生表作为查询的锚点:
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
| 归档时间: | 
 | 
| 查看次数: | 2773 次 | 
| 最近记录: |