您可以使用IIF()
表达式为每个年龄范围创建组,然后计算每个范围内的行数:
select AgeRange, count(*) as NumberOfOccurrences
from
(
SELECT
iif(age >= 0 and age <=9, "0-9",
iif(age>=10 and age <=19, "10-19", "20-29")) as AgeRange
FROM yourtable
) d
group by AgeRange
如果您有更多的年龄范围,那么您将向IIF()
.
另一种方法是添加一个包含报告年龄范围的表格。示例表可以是:
create table AgeRange
(
ageRangeStart number,
ageRangeEnd number
);
insert into AgeRange values
(0, 9),
(10, 19);
如果您创建此表,则可以将该表连接到现有表以报告范围:
SELECT r.agerangestart &" - "&r.agerangeend as AgeRange,
count(*) as NumberOfOccurrences
from agerange r
inner join test t
on t.age >= r.agerangestart
and t.age <= r.agerangeend
group by r.agerangestart &" - "&r.agerangeend
这两个查询都会给出结果:
+----------+---------------------+
| AgeRange | NumberOfOccurrences |
+----------+---------------------+
| 0 - 9 | 6 |
| 10 - 19 | 4 |
| 20 - 29 | 2 |
+----------+---------------------+
注意:这两个查询都在 MS Access 2003 中进行了测试。