I normally execute the following SQL queries in PostgreSQL 9.1 sequentially via psycopg2 every couple of seconds:
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';
Is it possible to do the same thing in a single select query such that I get a count for each type even if that count is zero. The following would work if it gave me the zero counts when there are zero for a given type.
select type, count(*) from bag group by type;
Thank you,
You can count multiple COUNT() for multiple conditions in a single query using GROUP BY. SELECT yourColumnName,COUNT(*) from yourTableName group by yourColumnName; To understand the above syntax, let us first create a table. The query to create a table is as follows.
You can use GROUP BY on two columns. In the following query, I use group by 1, 2 -- this is a convenient way to group by on the first two columns from SELECT clause. Also, I put two different count() to the query – probably, you will find that in your case it's more semantically correct to use count(distinct ..) .
The PostgreSQL COUNT function counts a number of rows or non-NULL values against a specific column from a table. When an asterisk(*) is used with count function the total number of rows returns. Syntax: COUNT (* | [DISTINCT] ALL | column_name)
PostgreSQL COUNT SELECT SELECT COUNT ( [*], [DISTINCT] [column_name] ) FROM TABLE_NAME; Let's dig a little deeper into the syntax shown above: SELECT – This is used to select certain columns from the database. COUNT – This is used to count the number of records in this table.
Use derived table as anchor of the query:
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
There can be many possible solutions for this. One is by generating all desired type in a subquery using UNION ALL
and do a LEFT JOIN
against bag
table. In this case, all the types
that you want to get will be shown on the result list and the non-existing type on table bag
will have zero count. This will almost work on all 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With