0

I have a table "users" where each user has a column "status" containing the value "1" or "2" or "3";

Now with a single mysqli query, I just want to count how many users with status = 1, how many users with status = 2, and how many users with status = 3

NB: The query must be count ONLY and no data has to selected or output except the number of each status.

I found other questions here covering nearly the same topic but they are not exactly the same.

Thanks.

2
  • 3
    SELECT status, count(*) FROM users GROUP BY status Commented Jun 24, 2016 at 12:30
  • 1
    How come the best answers are often found in the comments section? :-) Commented Jun 24, 2016 at 12:33

3 Answers 3

5

How about this:

SELECT 
  count(case when status = 1 then 1 else null end) AS STATUS_1,
  count(case when status = 2 then 1 else null end) AS STATUS_2,
  count(case when status = 3 then 1 else null end) AS STATUS_3
FROM users;

count will only count non-null entries and case-when will work on other databases as well.

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

1 Comment

Thanks for that but shall I use $row = $result->fetch_assoc(); or what as it didn't work?
2

This can be done by selectivity counting: just use a CASE expression inside count that only passed a non-null value for the desired rows:

SELECT count(CASE WHEN status = 1 THEN 1 END) status_1
     , count(CASE WHEN status = 2 THEN 1 END) status_2
     , count(CASE WHEN status = 3 THEN 1 END) status_3
  FROM users

This is the same as the nicer, but not nativley supported syntax using FILTER:

SELECT count(*) FILER(WHERE status = 1) status_1
     , count(*) FILER(WHERE status = 2) status_2
     , count(*) FILER(WHERE status = 3) status_3
  FROM users

Read more about this on my website modern SQL: http://modern-sql.com/feature/filter

Comments

1

Use something like this:

SELECT
SUM(IF(value=1,1,0)) as one,
SUM(IF(value=2,1,0)) as two,
SUM(IF(value=3,1,0)) as trhee
FROM users

The IF gives only a '1' back when your values is what you want it to be.

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.