PostgreSQL multiple count(),其中单个查询中的条件
我通常每隔几秒钟通过psycopg2在PostgreSQL 9.1中按顺序执行以下SQL查询:PostgreSQL multiple count(),其中单个查询中的条件,sql,postgresql,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'; 是否可
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查询中执行相同的操作,这样即使计数为零,也可以为每种类型获取计数。如果给定类型的计数为零,那么下面的方法可以工作
select type, count(*) from bag group by type;
谢谢,这方面有很多可能的解决方案。一种是使用
UNION all
在子查询中生成所有所需的类型,并对bag
表执行LEFT JOIN
。在这种情况下,您想要获得的所有类型
都将显示在结果列表上,并且表行李
上不存在的类型将具有零计数。这几乎适用于所有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
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
我在最后按类型抛出了一个订单,这正是我想要的。谢谢,谢谢你的帮助。非常感谢。