来自诺贝尔#14的SQLZOO SELECT

时间:2016-02-17 02:30:21

标签: sql select

在我整理出物理和化学科目后,我不知道如何订购这些名字!

  

问题:表达主语IN(' Chemistry',' Physics')可以是   用作值 - 它将为0或1。

     

显示1984年获奖者和主题按主题和获胜者名称排序;   但最后列出化学和物理。

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

问题更多详情http://sqlzoo.net/wiki/SELECT_from_Nobel_Tutorial

6 个答案:

答案 0 :(得分:4)

我在SQLZOO中尝试过,并且在SQL之后会给出正确的结果。

SELECT winner, subject
FROM nobel
WHERE yr=1984
ORDER BY subject IN ('Physics','Chemistry'), subject, winner

答案 1 :(得分:1)

in运算符不能像你一样在select中使用,但你使用order by子句中的case表达式在正确的路径上。你想要的是这个:

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

问题状态IN ('Physics','Chemistry')将评估为1或0,因此可以在某些数据库中使用完整的case表达式;虽然它不符合标准的ANSI SQL。我相信MySQL会允许它,但是例如MS SQL不会。

答案 2 :(得分:0)

select winner, subject
from nobel
where yr = '1984'
order by ( case subject
           when 'Chemistry' then 1
           when 'Physics'   then 2
           else 0
           end), subject, winner

答案 3 :(得分:0)

SELECT 
        winner, 
        subject
 FROM 
        nobel
 WHERE 
        yr=1984
 ORDER BY 
        subject IN ('Physics','Chemistry'),
        subject,
        winner

答案 4 :(得分:0)

正如@AllenJohnson 指出的,这是由 SQL 引擎设置引起的。

SQLZOO 使用了其问题指南中的表达式,但不指出 SQL Engine 会影响语法是否正确。

<块引用>

表达式主题 IN ('Chemistry','Physics') 可以用作值 - 它将是 0 或 1。

如果你选择你的 SQLZOO SQL Engine 作为 MySQL,你可以使用:

select 
    winner
    , subject
from nobel
where yr=1984
order by 
    subject in ('Physics','Chemistry')
    , subject
    , winner

如果您选择 SQLZOO SQL 引擎作为 Microsoft SQL,则可以使用:

select
    winner
    , subject
from nobel
where yr = 1984
order by
    case
        when subject in ('Physics', 'Chemistry') then 1
        else 0
    end
    , subject
    , winner

答案 5 :(得分:-1)

## Heading ##SELECT *
From (Select Top (Select count(winner) from nobel where yr = 1984 AND subject NOT IN ('Chemistry', 'Physics')) winner, subject
    FROM nobel
    WHERE yr=1984 AND subject NOT IN ('Chemistry', 'Physics')
    Order By subject, winner) AS zero
UNION
Select *
From (Select TOP (Select count(winner) from nobel where yr = 1984 AND subject IN ('Chemistry', 'Physics')) winner, subject
    From nobel
    Where yr = 1984 AND subject IN ('Chemistry', 'Physics')
    Order By subject, winner) AS one

显示结果但不正确答案。