Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLZOO SELECT from nobel #14

Tags:

sql

select

I don't know how to order the names after I sorted out the subject physics and chemistry!

Question: The expression subject IN ('Chemistry','Physics') can be used as a value - it will be 0 or 1.

Show the 1984 winners and subject ordered by subject and winner name; but list Chemistry and Physics last.

SELECT winner, subject, subject IN('Physics', 'Chemistry')
FROM nobel
WHERE yr=1984
ORDER BY CASE
 WHEN subject IN ('Physics', 'Chemistry') = 0 THEN subject IN ('Physics', 'Chemistry')
 WHEN subject IN ('Physics', 'Chemistry') =  THEN winner
 ELSE winner 
End

url to problem for more details http://sqlzoo.net/wiki/SELECT_from_Nobel_Tutorial

like image 484
Matthew Chun Avatar asked Feb 17 '16 02:02

Matthew Chun


2 Answers

I have tried in SQLZOO and following SQL gives correct result.

SELECT winner, subject
FROM nobel
WHERE yr=1984
ORDER BY subject IN ('Physics','Chemistry'), subject, winner
like image 182
Dylan Su Avatar answered Sep 20 '22 20:09

Dylan Su


The in operator can't be used in the select as you did, but you were on the right path using a case expression in the order by clause. What you want is this:

SELECT 
  winner, subject
FROM 
  nobel
WHERE 
  yr = 1984
ORDER BY 
  CASE WHEN subject IN ('Physics','Chemistry') THEN 1 ELSE 0 END, 
  subject, 
  winner

As the problem states IN ('Physics','Chemistry') will evaluate to 1 or 0 so it can be used instead on the full case expression in some databases; though it's not conformant with standard ANSI SQL. MySQL will allow it I believe, but for example MS SQL will not.

like image 45
jpw Avatar answered Sep 21 '22 20:09

jpw