sql查询计数为零

时间:2010-09-10 11:24:40

标签: sql oracle

我有这个sql查询从一个包含3列的表中检索ID:ID,Country和Age

SELECT Country, 
(CASE 
 WHEN AGE BETWEEN 0 AND 9 THEN '0-9'
 WHEN AGE BETWEEN 10 AND 19 THEN '10-19'
 WHEN AGE BETWEEN 20 AND 29 THEN '20-29'
 WHEN AGE BETWEEN 30 AND 39 THEN '30-39'
 WHEN AGE BETWEEN 40 AND 49 THEN '40-49'
 ELSE '50+'
END) Age_Bins, COUNT (DISTINCT ID)
FROM MYTABLE
GROUP BY Country, Age_Bins;

我得到的结果如下:

UK '0-9' 7; 
UK '20-29' 14; 
etc... 

但我想要的还有英国'10 -19'0(该年龄段没有身份证)。如何相应地修改sql代码以使输出具有零计数。感谢

2 个答案:

答案 0 :(得分:8)

理想情况下,您需要一个“年龄箱”表和一个国家/地区表,如下所示:

select c.Country, b.age_bin, count(distinct m.id)
from countries c
cross join age_bins b
left outer join mytable m on m.country = c.country
                          and m.age between b.min_age and b.max_age

如果有必要,你可以伪造这样的表:

WITH countries as (select distinct country from mytable),
     age_bins as (select '0-9' age_bin, 0 min_age, 9 max_age from dual
                  union all
                  select '10-19' age_bin, 10 min_age, 19 max_age from dual
                  union all
                  ...
                 ),
select c.Country, b.age_bin, count(distinct m.id)
from countries c
cross join age_bins b
left outer join mytable m on m.country = c.country
                          and m.age between b.min_age and b.max_age

答案 1 :(得分:4)

您可以将每个age-bin创建为基于案例的列,返回0或1,并使用SUM()而不是COUNT()

 select V.country, sum(V.Zero2Nine) as [0-9], sum(V.Ten2Nineteen) as [10-19] ...
 from
 (
  select country,
   (case when age between 0 and 9 then 1 else 0 end) as Zero2Nine,
   (case when age between 10 and 19 then 1 else 0 end) as Ten2Nineteen
   from ...
  )  as V

 group by  V.country