SQL(DB2) - 如果未找到记录则返回零

时间:2015-02-20 17:41:10

标签: sql db2 sas

如何更改此查询以便为找不到行的每个区域显示零?

    proc sql;
create table test as
select count(acct_num) as total_count,
       region
    from
        table1
    group by region
    ;
run;

理想情况下,我希望看到这一点:

Region1   500
Region2   0
Region3   20
Region4   0

1 个答案:

答案 0 :(得分:2)

假设您有一张包含所需区域的表格,您可以使用left join

select r.region, count(t.acct_num) as total_count
from regions r left join
     table1 t
     on r.region = t.region
group by r.region;

如果您没有这样的表格,您可以通过以下方式即时创建一个表格:

select r.region, count(t.acct_num) as total_count
from (select 'region1' as region from sysibm.sysdummy1 union all
      select 'region2' from sysibm.sysdummy1 union all
      . . .
     ) r left join
     table1 t
     on r.region = t.region
group by r.region;