简体   繁体   中英

MySQL - Different WHERE clauses to same column

I have a situation where I need to create columns depending on their content.

For instance, here is SQLFiddle - http://sqlfiddle.com/#!2/0ec7a/1 .

I need to get a result like this:

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

How do I go about this?

I'm looking at CASE WHEN statements and IF statements from the MySQL Manual, but a clearer explanation would be very useful.

You don't even need CASE !

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

See this working in SQLFiddle .

The reason this works is that in mysql, true is 1 and false is 0 , so summing a condition counts how many times it was true!

For (most?) other databases, you must use the boring case inside the sum: sum(case when gender = 'm' then 1 else 0 end) etc

This type of data layout is called a "pivot" . Some databases, like Oracle, support it natively through specific extensions to its flavour of SQL, but in mysql you have to "roll your own".

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

You can also do prepared statement

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM