COUNTIF is an Excel function to count cells in a range that meet a single condition. COUNTIF can be used to count cells that contain dates, numbers, and text. The criteria used in COUNTIF supports logical operators (>,<,<>,=) and wildcards (*,?) for partial matching. A number representing cells counted.
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.
CASE can be used in conjunction with SUM to return a count of only those items matching a pre-defined condition. (This is similar to COUNTIF in Excel.) The trick is to return binary results indicating matches, so the "1"s returned for matching entries can be summed for a count of the total number of matches.
SQL Count Function: We can specify to count only unique values by adding the DISTINCT keyword to the statement.
In Postgres 9.4 or later, use the aggregate FILTER
option. Typically cleanest and fastest:
SELECT category
, count(*) FILTER (WHERE question1 = 0) AS zero
, count(*) FILTER (WHERE question1 = 1) AS one
, count(*) FILTER (WHERE question1 = 2) AS two
FROM reviews
GROUP BY 1;
Details for the FILTER
clause:
If you want it short:
SELECT category
, count(question1 = 0 OR NULL) AS zero
, count(question1 = 1 OR NULL) AS one
, count(question1 = 2 OR NULL) AS two
FROM reviews
GROUP BY 1;
More syntax variants:
crosstab()
yields the best performance and is shorter for long lists of options:
SELECT * FROM crosstab(
'SELECT category, question1, count(*) AS ct
FROM reviews
GROUP BY 1, 2
ORDER BY 1, 2'
, 'VALUES (0), (1), (2)'
) AS ct (category text, zero int, one int, two int);
Detailed explanation:
The "best" way (for me) is to write a query like:
SELECT
category,
question1,
count(*)
FROM reviews
GROUP BY category, question1
Then I use this data to draw a table in application logic.
Other option is to use one JSON column for all grouping results. This will result in something like:
category1 | {"zero": 1, "one": 3, "two": 5}
category2 | {"one": 7, "two": 4}
and so on.
The query for this option you can build from the previous one with json_build_object
and json_agg
. The best thing for this option - you do not need to know number of possible question1
values ahead of time.
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