MySQL - 按多行分组

时间:2012-04-14 13:36:41

标签: mysql group-by

我有一个针对我的用户的在线调查,每次用户回答调查时,我都会在“survey_stats”表中捕获他们的详细信息 -

| id      | user_id | survey_id | key          | value   |
|---------|---------|-----------|--------------|---------|
|       1 |      10 |        99 | gender       | male    |
|       2 |      10 |        99 | age          | 32      |
|       3 |      10 |        99 | relationship | married |
|       4 |      11 |        99 | gender       | female  |
|       5 |      11 |        99 | age          | 27      |
|       6 |      11 |        99 | relationship | single  |

换句话说,当用户回答调查时,我会在3行中捕获用户的属性(性别,年龄,关系)(每行有关用户的每个独立属性)。我们保持这种方式的原因是,如果我们希望将来扩展用户属性,我们可以在每次调查中添加更多记录,而不是修改survey_stats表结构。

我想构建一个SQL来生成这样的报告:

| age_group | male  |  female |
|-----------|-------|---------|
|   13 - 17 |    10 |       7 |
|   18 - 24 |    25 |      10 |
|   25 - 34 |    30 |      11 |

非常感谢一些帮助,告诉我如何编写单个SQL语句来执行此操作。

仅供参考 - 我正在使用MySQL。该项目是Ruby on Rails应用程序。

非常感谢。

1 个答案:

答案 0 :(得分:4)

select
      case when YT2.age between 13 and 17 then "13 - 17"
           when YT2.age bewteen 18 and 24 then "18 - 24"
           when YT2.age between 25 and 35 then "25 - 34"
           else "35 and over" end as AgeGroup,
      Sum( if( YT1.value = "male", 1, 0 )) as MaleFlag,
      SUM( if( YT1.value = "female", 1, 0 )) as FemaleFlag
   from
      YourTable YT1
         JOIN YourTable YT2
             ON YT1.user_id = YT2.user_ID
            AND YT1.survey_id = YT2.survey_id
            AND YT2.key = "age"
   where
      YT1.Key = "gender"
   group by
      AgeGroup