The table is like:
country | fruit | size |
---|---|---|
Japan | Apple | Big |
Japan | Apple | Small |
Japan | Orange | Big |
Singapore | Banana | Small |
The expect output is like:
country | type | total |
---|---|---|
Japan | 2 | 3 |
Singapore | 1 | 1 |
I managed to run the counts separately.
Fruit type:
SELECT country, COUNT(DISTINCT fruit) AS type
FROM Table
GROUP BY country
Fruit total:
SELECT COUNT(fruit)
FROM Table
GROUP BY country
2
Answers
You can combine your queries into one :
Like has been commented, you can simply put both aggregates in the same
SELECT
list.count(*)
is faster. One difference: it counts all rows, whilecount(fruit)
only counts non-null values. If fruit isNOT NULL
, both do the same.count(DISTINCT ...)
is comparatively expensive. Depending on Postgres version and data distribution, this may be faster (doing the same):