MySQL - 同一列的不同WHERE子句

时间:2012-11-22 01:49:20

标签: mysql sql pivot case

我遇到需要根据内容创建列的情况。

例如,这里是SQLFiddle - http://sqlfiddle.com/#!2/0ec7a/1

我需要得到这样的结果:

--------------------------
| CITY | MALES | FEMALES |
--------------------------
| NY   | 5     | 2       |
--------------------------
| DC   | 2     | 1       |
--------------------------

我该怎么做?

我正在查看MySQL手册中的CASE WHEN语句和IF语句,但更清楚的解释将非常有用。

2 个答案:

答案 0 :(得分:6)

您甚至不需要CASE

SELECT
    city,
    sum(gender = 'm') as males,
    sum(gender = 'f') as females
FROM Population
group by city

请参阅此working in SQLFiddle

这样做的原因是,在mysql中,true1false0,因此总结条件会计算出它的真实次数!

对于(大多数?)其他数据库,您必须在总和中使用枯燥的案例:sum(case when gender = 'm' then 1 else 0 end)

此类数据布局称为"pivot"。有些数据库,比如Oracle,通过对SQL风格的特定扩展本身支持它,但是在mysql中你必须“自己动手”。

答案 1 :(得分:1)

SELECT  CITY,
        SUM(CASE WHEN GENDER = 'M' THEN 1 ELSE 0 END) MALE,
        SUM(CASE WHEN GENDER = 'F' THEN 1 ELSE 0 END) FEMALE
FROM Population
GROUP BY City

您也可以做预备陈述

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'SUM(CASE WHEN GENDER = ''',
      GENDER,
      ''' then 1 ELSE 0 end) AS ',
      GENDER
    )
  ) INTO @sql
FROM Population;

SET @sql = CONCAT('SELECT  CITY, ', @sql, ' 
                   FROM Population
                    GROUP BY City');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;