1

I have data like below and trying to get the count of each column per row . How to do it in a SQL/ POSTGRESQL ?

Movie Horror Comedy
AAA Y Y
bbb N N
CCC Y N
DDD Y Y

How to get the count of each column with a Y in POSTGRES with the expected output like this

Category count
Horror 3
Comedy 2

1 Answer 1

3

Probably the simplest method is union all:

select 'Horror', count(*)
from t
where horror = 'Y'
union all
select 'Comedy', count(*)
from t
where Comedy = 'Y';

But in Postgres, I would instead suggest a lateral join:

select genre, count(*)
from t cross join lateral
     (values ('Horror', horror), ('Comedy', comedy)
     ) v(genre, flag)
where flag = 'Y'
group by genre;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I was looking for the POSTGRES solution. That worked

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.