0

我正在尝试创建一个处理两个表的查询:

表:地区

Column Name     Type      Constraint
REGION_Cd       Number    Primary Key
REGION_Desc     String

表:统计

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 语句,对吗?

4

2 回答 2

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
于 2013-04-12T23:17:09.947 回答
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
于 2013-04-12T23:19:26.707 回答