我有这个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;
Run Code Online (Sandbox Code Playgroud)
我得到的结果是这样的:
UK '0-9' 7;
UK '20-29' 14;
etc...
Run Code Online (Sandbox Code Playgroud)
但我想要的还有英国'10 -19'0(该年龄段没有身份证).如何相应地修改sql代码以使输出具有零计数.谢谢
理想情况下,您需要一个"年龄箱"表和一个国家表,如下所示:
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
Run Code Online (Sandbox Code Playgroud)
如果有必要,你可以像这样伪造表格:
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
Run Code Online (Sandbox Code Playgroud)