Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PostgreSQL multiple count(),其中单个查询中的条件_Sql_Postgresql - Fatal编程技术网

PostgreSQL multiple count(),其中单个查询中的条件

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'; 是否可

我通常每隔几秒钟通过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查询中执行相同的操作,这样即使计数为零,也可以为每种类型获取计数。如果给定类型的计数为零,那么下面的方法可以工作

 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

我在最后按类型抛出了一个订单,这正是我想要的。谢谢,谢谢你的帮助。非常感谢。