0

I want get all users with a number of orders with division status

MY QUERY:

SELECT 
    users.id as "Id", 
    users.firstname as "Firstname", 
    users.lastname as "Lastname",
    COUNT(IF(orders.status = 0, 1, 0)) as "Status #0",
    COUNT(IF(orders.status = 1, 1, 0)) as "Status #1",
    COUNT(IF(orders.status = 2, 1, 0)) as "Status #2",
    COUNT(IF(orders.status = 3, 1, 0)) as "Status #3",
    COUNT(IF(orders.status = 4, 1, 0)) as "Status #4",
    COUNT(IF(orders.status = 5, 1, 0)) as "Status #5",
    COUNT(IF(orders.status = 6, 1, 0)) as "Status #6",
    COUNT(IF(orders.status = 7, 1, 0)) as "Status #7",
    COUNT(IF(orders.status = 8, 1, 0)) as "Status #8"
FROM 
    users 
    LEFT JOIN orders ON orders.idu = users.id 
WHERE 
    users.register_complete = 1 
GROUP BY 
    users.id 
ORDER BY 
    users.date_register DESC

Result: enter image description here

All status is to same.... where is problem? Thanks! :)

2
  • 1
    Change COUNT to SUM and you are done! Commented Sep 29, 2016 at 8:33
  • Use Sum instead of using Count Commented Sep 29, 2016 at 8:33

1 Answer 1

3

count(value) will count as 1 if value is something else than null, see documentation:

COUNT(expr)

Returns a count of the number of non-NULL values of expr in the rows retrieved by a SELECT statement. The result is a BIGINT value.

So you counted every row, independent from your IF-condition.

Either change your count into sum, or change 0 into null to get the desired result:

...
COUNT(IF(orders.status = 0, 1, null))
...
Sign up to request clarification or add additional context in comments.

2 Comments

Great news! Thanks you!
note sum(IF(orders.status = 0, 1, 0)) will return null instead of 0 if there are no rows matching the where conditions, which is probably not what you want. So I recommend using count()

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.