gpt4 book ai didi

mysql - SQL显示年龄范围

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

我正在写一个年龄范围的查询,我想在其中显示所有年龄段的人数,例如

    AGE   PEOPLE
"0-10" 0
"11-20" 2
"21-30" 5
"31-40" 0
"41-50" 1

我试过

SELECT SUM(CASE WHEN age < 10 THEN 1 ELSE 0 END) AS [Under 10],
SUM(CASE WHEN age BETWEEN 11 AND 20 THEN 1 ELSE 0 END) AS [11-20],
SUM(CASE WHEN age BETWEEN 21 AND 30 THEN 1 ELSE 0 END) AS [21-30]
FROM people

但是它将范围显示为列名

   0-10  11-20 21-30 31-40 41-50
0 2 5 0 1

这是我不想要的。

我也试过 GROUP BY 但它没有显示计数为 0 的范围。

最佳答案

您可以使用UNION ALL:

SELECT '[Under 10]' as Age, SUM(CASE WHEN age < 10 THEN 1 ELSE 0 END) as People
FROM people
UNION ALL
SELECT '[11-20]', SUM(CASE WHEN age BETWEEN 11 AND 20 THEN 1 ELSE 0 END)
FROM people
UNION ALL
SELECT '[21-30]', SUM(CASE WHEN age BETWEEN 21 AND 30 THEN 1 ELSE 0 END)
FROM people;

关于mysql - SQL显示年龄范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57603617/

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