0

I have a table and would like to count the appearance of the values (no sum)

ID  status
============
1   2
2   3
3   1
4   1
5   1
6   2

and I need following result:

status_1 status_2 status_3 status_4
===================================
3        2        1        0

Can I do this with a single SQL statement?

1
  • 1
    Consider handling issues of data display at the application level (if you have one) Commented Jul 15, 2013 at 13:18

6 Answers 6

2
select
sum(if(status=1,1,0)) as status_1,
sum(if(status=2,1,0)) as status_2,
sum(if(status=3,1,0)) as status_3,
sum(if(status=4,1,0)) as status_4
from foo
Sign up to request clarification or add additional context in comments.

Comments

0

Use a group query, with a count function:

select status, count(status)
from tablename
group by status

Comments

0
Select 
   sum(case status When 1 Then 1 End) status1,
   sum(case status When 2 Then 1 End) status2,
   sum(case status When 3 Then 1 End) status3,
   sum(case status When 4 Then 1 End) status4,
   etc.
From table

2 Comments

This should have else 0 to match the output in the question.
Charles - I prefer CASE over IF because it's more "standard", but your answer will show NULL for status4, whereas the OP wants it to be zero.
0

Is important to notice that what you are asking would imply a code modification as the supported status change. I think it could be better to have the result in several lines. This one could give you the same resuts in several rows:

SELECT COUNT(DISTINCT status) FROM mytable;

So you can iterate over the hole time, without query modifications. Hope that helps

Comments

0

Try this one will help you

select status, count(*) from tablename
group by status

Comments

0
select count(status) where status = x

Would yield the count for a single status.

Perhaps you could nest this statement but that may be inefficient.

Edit: Group By is the way to go. See other answer.

Comments

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.