My table content:
id aid
----------
1 1
2 2
3 2
4 4
5 4
my sql: select count(*) from table where aid in (1,2,3,4) group by aid
result:
count(*)
----------
1
2
2
I would like result:
count(*)
----------
1
2
0
2
I want a count result when aid is 1,2,3,4. What a sql should I use? Thanks for help.
(I‘m use MySQL)
Time for an obvious statement:
– Data can’t “magically appear”, it needs to exist somewhere for it to appear in the output.
This is relevant for your desire to have a count of
0foraid = 3. Because there isn’t a record withaid = 3, it can’t be counted. It’s data that doesn’t exist so will never appear in the output. So we need to force it to exist.If you have a table that lists all of the
aidentities, that’s easy to do with aLEFT JOIN…(
COUNT(yourDataTable.aid)does not count records where the field isNULL. So the3now exists, and theCOUNT()can return0.)