如何创建一个SQL查询,根据年龄范围和性别对最近90天的活跃访客进行分解,其中年龄在21-25之间,然后是10年增量到75+,并声明年龄范围以便于调整?
答案 0 :(得分:1)
通常我会像
一样使用CASE, CASE WHEN table.AGE > 20 and < 26 THEN '21-25'
WHEN table.AGE > 25 and < 36 THEN '26-35'
WHEN table.AGE > 35 and < 46 THEN '36-45'
--and so on
ELSE NULL END AS AGE_GROUP
答案 1 :(得分:0)
我的主要问题是如何获得年龄范围(其他条件应该是直接的)。您可以通过case语句定义范围,然后按此列分组:
select CASE
WHEN age between 21 and 24 THEN '21..24'
WHEN age between 25 and 34 THEN '25..34'
WHEN age between 35 and 44 THEN '35..44'
END as agerange, count(*)
from (select 23 as age
union
select 40 as age
union
select 41 as age) as ages
group by agerange
结果:
agerange |count(*)
---------|--------
21..24 |1
35..44 |2