4

In mysql, I got table "scores" as follow

Id  Date                Name        score
1   2011-08-24 00:00:00 sharique    10
2   2011-08-24 00:00:00 joe     11
3   2011-08-24 00:00:00 vijay       5
4   2011-08-25 00:00:00 sharique    0
5   2011-08-25 00:00:00 joe    11

Now when I am running query

SELECT date,count(id) as count FROM scores where `name` = 'vijay' group by `date`;

I am getting result as

date                 count
2011-08-24 00:00:00,  1

instead of

date                 count
2011-08-24 00:00:00,  1
2011-08-25 00:00:00,  0

how can i display result with zero count, please?

3
  • 3
    It's the expected result. You only have vijay once in your dataset.. Commented Nov 21, 2011 at 12:59
  • 2
    it is not the expected result. He wants to show all dates including the days without having vijay Commented Nov 21, 2011 at 13:06
  • That’s true, I want to display result with zero count, maybe it is expected result for a given query, but my problem is to display count for each day including zero, so that I can say on which day “vijay” did not play or score anything Commented Nov 21, 2011 at 13:12

2 Answers 2

9

Here's one simple way:

SELECT s2.date, count(s1.id) as count
FROM (select distinct `date` from scores) s2 
  left join scores s1
    on  s1.`date` = s2.`date`
    and s1.`name` = 'vijay'
group by 1

This guarantees a date for everybody for every distinct date in the table

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

3 Comments

My thoughts exactly (except typed faster :) )
It's the other way around: (select distinct ...) left join scores
thanks to all, it is working now... special thanks to @ypercube
0

It is The Expected Result as You Are Counting the number of rows that matches your where condition.

SELECT date,count(id) as count FROM scores where `name` = 'vijay' group by `date`;

It selects only one record hence the result of count is 1.

If you want to count all the rows use don't restrict the data by using Where Clause e.g:-

SELECT date,count(id) as count FROM scores group by `date`;

Like wise the following query will return 3 as count..

SELECT date,count(id) as count FROM scores where id in (1,2,3) group by `date`;

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.