[英]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 . 例如,这是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. 我正在看《 MySQL手册》中的
CASE WHEN
语句和IF
语句,但是更清晰的解释将非常有用。
You don't even need CASE
! 您甚至都不需要
CASE
!
SELECT
city,
sum(gender = 'm') as males,
sum(gender = 'f') as females
FROM Population
group by city
See this working in SQLFiddle . 请参见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! 这样做的原因是,在mysql中,
true
为1
, false
为0
,因此对一个条件求和就算它为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 对于(大多数?)其他数据库,您必须在sum内使用无聊的大小写:
sum(case when gender = 'm' then 1 else 0 end)
等等
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".
一些数据库,例如Oracle,通过对其SQL风格的特定扩展来本地支持它,但是在mysql中,您必须“自己滚动”。
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.