2

Suppose I have this table:

|MY_TABLE|
| ID_COL |
|   1    |
|   1    |
|   2    |
|   2    |

Now I want to do a count query on this table that would include zero results. When I try to run my query:

Select ID_COL,count(ID_COL) 
from   MY_TABLE 
where ID_COL = '1' or ID_COL = '2' or ID_COL = '100' group by ID_COL

The result will only be two rows. I want to display 0 for ID_COL = '100'. Is there a way to do this?

Thanks.

BTW, I am using DB2.

jaypax123
  • 188
  • 2
  • 14

1 Answers1

2

You would have to create a table on the fly to contain a record per ID:

select 1 as id_col union all select 2 union all select 100;

Then you can select IDs from this table and show the count:

select all_ids.id_col, count(my_table.id_col)
from (select 1 as id_col union all select 2 union all select 3) all_ids
left join my_table on my_table.id_col = all_ids.id_col
group by all_ids.id_col;

EDIT: Now that you tagged your request with DB2: DB2 needs a dummy table to select one value from. Rather then select 1 one must write select 1 from sysibm.sysdummy1. The complete query:

select all_ids.id_col, count(my_table.id_col)
from 
(
  select 1 as id_col from sysibm.sysdummy1
  union all 
  select 2 from sysibm.sysdummy1
  union all 
  select 3 from sysibm.sysdummy1
) all_ids
left join my_table on my_table.id_col = all_ids.id_col
group by all_ids.id_col;
Thorsten Kettner
  • 89,309
  • 7
  • 49
  • 73