How I can flatten a count table in postgresql that contains only 2 columns with crosstab?

All we need is an easy explanation of the problem, so here it is.

In my database I have the following table:

Mytable
id SERIAL,
category VARCHAR,
value VARCHAR

And I execute the following query:

select category, COUNT(*) from mytable group by category

What I want is to generate a single row value containing the following:

category1 | category2 |  category3
1234      | 3456      |  12345

The table return the following results:

 category   | Value
`category1` | 1234
`category2` | 3456
`category3` | 12345

Do you have any idea how to do this?
I have looked the crosstab function but required an extra column named row_name that in my cases does not exist. Also using a second query seems like a waste to me.

The

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Use conditional aggregation:

select count(*) filter (where category = 'category1') as category1,
       count(*) filter (where category = 'category2') as category2,
       count(*) filter (where category = 'category3') as category3
from the_table;

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply