我试图创建一个处理两个表的查询:
表:REGION
Column Name Type Constraint
REGION_Cd Number Primary Key
REGION_Desc String
表:STATS
Column Name Type Constraint
AGE Number Primary Key
REGION Number Foreign Key to REGION (REGION_Cd)
POPULATION Number
我如何创建一个查询,以便找到两个年龄组(0-15,16-30)的人口并以下列格式显示:
Region_Desc AgeGroup Population
South 0‐15 11253
South 16‐30 235234
由于AgeGroup列实际上不是表中的一列,我应该使用AS语句,对吗?
答案 0 :(得分:1)
也许类似......但它假设你想要年龄组/地区的人口总和。根据数据库中人口的工作方式,这可能是也可能不正确
Select Region_Desc, case when age between 0 and 15 then '0-15'
when age between 16 and 30 then '16-30'
else 'over 30' end as AgeGroup,
sum(Population) as Population
FROM Region INNER JOIN STATS on region_Cd = Region
GROUP BY Region_DESC, AgeGroup
答案 1 :(得分:0)
SELECT Region_DESC, AgeGroup, Population
FROM
(select REGION, sum(POPULATION) as Population, '0-15' AS AgeGroup
from STATS
Where Age between 0 and 15
group by REGION
union
Select REGION, SUM(POPULATION) as Population, '16-30' As AgeGroup
from STATS
Where Age between 16 and 30
group by REGION) s
join REGION on REGION_CD = REGION