微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

sql fiddle demo

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐