2

我为我的用户进行了在线调查,每次用户回答调查时,我都会在这样的“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 应用程序。

非常感谢。

4

1 回答 1

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
于 2012-04-14T13:55:25.623 回答