gpt4 book ai didi

mysql - 年龄组之间的sql

转载 作者:行者123 更新时间:2023-11-29 02:04:15 25 4
gpt4 key购买 nike

希望你能帮帮我!

我有以下数据库:

country | Date_of_birth
-----------------------
france | 1980-07-01
spain | 1978-03-23
greece | 1981-05-05
germany | 1974-08-11

我试图得到这个结果:

country | 13 - 17 | 25 - 45 | 65 - 75
-------------------------------------
france | | 1 |
spain | | 1 |
greece | | 1 |

到目前为止我想出的查询:

SELECT SUM( IF( age BETWEEN 13 AND 17 , 1, 0)) AS '13 - 17', 
SUM( IF( age BETWEEN 25 AND 45 , 1, 0)) AS '25 - 45',
SUM( IF( age BETWEEN 65 AND 75 , 1, 0)) AS '65 - 75'
FROM (SELECT TIMESTAMPDIFF( YEAR, Date_of_birth, CURDATE()) AS age, country FROM data
) AS test
GROUP BY country
HAVING country IN ("france","greece,"spain")

结果:

 13 - 17 | 25 - 45 | 65 - 75
----------------------------
| 1 |
| 1 |
| 1 |

知道我如何在开头获得“国家/地区”列吗?

提前致谢!

最佳答案

Having 仅适用于聚合 列。你想要一个简单的 where:

SELECT 
country,
SUM(age BETWEEN 13 AND 17) AS '13 - 17',
SUM(age BETWEEN 25 AND 45) AS '25 - 45',
SUM(age BETWEEN 65 AND 75) AS '65 - 75'
FROM (SELECT TIMESTAMPDIFF( YEAR, Date_of_birth, CURDATE()) AS age, country FROM data
) AS test
WHERE country IN ('france', 'greece', 'spain')
GROUP BY country

还要注意查询的简化:在 mysql 中 true1false0,所以您可以简单地对条件求和 - 您不需要 case

此外,您有一个语法错误 - 您需要在国家/地区值周围加上单引号。

关于mysql - 年龄组之间的sql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9385473/

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