sql在年龄组之间

时间:2012-02-21 21:30:41

标签: mysql

希望你能帮助我!

我有以下数据库:

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   |

我知道如何在开始时获得“国家/地区”专栏吗?

提前致谢!!

3 个答案:

答案 0 :(得分:2)

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

此外,您遇到语法错误 - 您需要在您的国家/地区值附近使用单引号。

答案 1 :(得分:1)

如果您想要包含“country”列,则必须将其添加到SELECT部分​​:

SELECT
   country, 
   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")

答案 2 :(得分:0)

SELECT country, SUM...., SUM..., SUM...