Data source as follows:
name course
---------------
Marry UNIX
Bob Java
Bob SQL
Cherry SQL
John SQL
John UNIX
Eric SQL
this sql is correct:
SELECT name,
max(CASE WHEN course = 'SQL' THEN '○' ELSE null END) AS "SQL",
max(CASE WHEN course = 'UNIX' THEN '○' ELSE null END) AS "UNIX",
max(CASE WHEN course = 'Java' THEN '○' ELSE null END) AS "Java"
FROM Courses
GROUP BY name;
but this is wrong:
SELECT name,
max(CASE WHEN course = 'SQL' THEN '○' ELSE 'x' END) AS "SQL",
max(CASE WHEN course = 'UNIX' THEN '○' ELSE 'x' END) AS "UNIX",
max(CASE WHEN course = 'Java' THEN '○' ELSE 'x' END) AS "Java"
FROM Courses
GROUP BY name;
I ran the second one in MySQL,and the result is wrong
name SQL UNIX JAVA
Bob x x x
Cherry ○ x x
Eric ○ x x
John x x x
Marry x ○ x
so what's the problem between these two sql? MAX() ignore null?
MAX()
ignores null values, and picks the max value otherwise seen. Since 'x'
is larger than 'o'
, if both values are present, the result is 'x'
.
Eg for Bob, since there are 2 records with different course
value, at least one of the record will hit the else
clause. Which means that for all 3 of them, at least one 'x'
is present, and so the result is 'x'
for all 3.
Basically, the first version is: "If the WHEN
clause is true for any record, the result is 'o'
, otherwise the result is NULL
."
The second version is: "If the WHEN
clause is false for any record, the result is 'x'
, since that is the highest value, otherwise the result is 'o'
." Or said another way: "If the WHEN
clause is true for all records, the result is 'o'
, otherwise the result is 'x'
."
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.