0

I am new in sql. I want to count something like:

Select count(*) from table where col1= x and col2=x and Col3=x. 

I need to count the same value in all different column. Any help will be appreciated.

1 Answer 1

2

You can use conditional aggregation :

Select sum(case when col1='x' then 1 else 0 end) as count_col1,
       sum(case when col2='x' then 1 else 0 end) as count_col2,
       sum(case when col3='x' then 1 else 0 end) as count_col3
  from tab;

If you want to have sum of these count values, consider the above query as an inner and use the following :

 Select q.*,
        q.count_col1 + q.count_col2 + q.count_col3 whole_sum
   from     
     (
        Select sum(case when col1='x' then 1 else 0 end) as count_col1,
               sum(case when col2='x' then 1 else 0 end) as count_col2,
               sum(case when col3='x' then 1 else 0 end) as count_col3
          from tab  
      ) q

Rextester Demo

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for your reply. Do I can sum of all the columns value as well?
@AyesaJannat Welcome, yes, sure depending on your data's syntax.
What to do for having the total of 3 columns count?
Wow!! Thanks a lot.
Even simpler is sum the conditions without case: sum(col1='x') as count_col1,
|

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.