我想查询某地区各年龄段的人数。
语句为:select 年龄,conut(ID) from 人口 where 年龄 between 15 and 20 group by 年龄 order by 年龄
虽然查询出了结果,但是如果某个年龄段没有人,该年龄就不会显示。我想的是不管有没有人查询的列表都是完整的15-20岁
如:
年龄 人口
15 262
16 258
18 59
19 206
20 15617岁没有人,没有显示。我想要17岁也显示出来。该怎么办呢?
语句为:select 年龄,conut(ID) from 人口 where 年龄 between 15 and 20 group by 年龄 order by 年龄
虽然查询出了结果,但是如果某个年龄段没有人,该年龄就不会显示。我想的是不管有没有人查询的列表都是完整的15-20岁
如:
年龄 人口
15 262
16 258
18 59
19 206
20 15617岁没有人,没有显示。我想要17岁也显示出来。该怎么办呢?
insert @人口 select 16,10
insert @人口 select 18,23
insert @人口 select 19,2
insert @人口 select 20,10
select isnull(a.年龄,b.id) 年龄, isnull(人口,0) 人口
from @人口 a
right join (select 15 as id union select 16 union select 17 union select 18 union select 19 union select 20) b
on 年龄= b.id/*
年龄 人口
----------- -----------
15 2
16 10
17 0
18 23
19 2
20 10(所影响的行数为 6 行)*/
insert @人口 select 15,2
insert @人口 select 16,10
insert @人口 select 18,23
insert @人口 select 19,2
insert @人口 select 20,10--@Satre ,@End可以随便改
declare @Satre int ,@End int
set @Satre=15
set @End=20
declare @人口临时 table( 年龄 int, 人口 int)
while @Satre<=@End
begin
insert @人口临时 select @Satre,0
set @Satre=@Satre+1
endselect * from (
select 年龄,人口 from @人口
union all
select 年龄,人口 from @人口临时 a where not exists (select 年龄 from @人口 b where a.年龄=b.年龄)) as c
order by 年龄 asc/*
年龄 人口
----------- -----------
15 2
16 10
17 0
18 23
19 2
20 10
*/