PostgreSQL多次count()在单个查询中的条件
发布时间:2020-12-13 16:01:31 所属栏目:百科 来源:网络整理
导读:我通常每隔几秒通过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 ba
我通常每隔几秒通过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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |