gpt4 book ai didi

SQL 按年龄范围分组

转载 作者:行者123 更新时间:2023-12-02 14:17:05 25 4
gpt4 key购买 nike

SQL 2005,我有一个包含“ages_c”列的表,我需要按年龄范围对记录进行分组。这是我在这个网站上找到的查询,它让我达到了 90%,但“分组依据”出错,*列名“age_range”无效*

 select 
case
when age_c <18 then 'Under 18'
when age_c between 18 and 24 then '18-24'
when age_c between 25 and 34then '25-34'
END as age_range,
Count(*) as count
from contacts
group by age_range
order by age_range

当我按“age_c”分组和排序时,我的结果是:

  Under 18  1
18-24 1
18-24 1
25-34 1

我想要的是:

 Under 18   1
18-24 2
25-34 1

谢谢。

最佳答案

试试这样:

 SELECT SUM(CASE WHEN age_c < 18 THEN 1 ELSE 0 END) AS [Under 18],
SUM(CASE WHEN age_c BETWEEN 18 AND 24 THEN 1 ELSE 0 END) AS [18-24],
SUM(CASE WHEN age_c BETWEEN 25 AND 34 THEN 1 ELSE 0 END) AS [25-34]
FROM contacts

关于SQL 按年龄范围分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8762886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com