sql

sqlzoo - SELECT from nobel

yjs3819 2021. 7. 16. 18:55
728x90

SQL

  1. SELECT yr, subject, winner
    FROM nobel
    WHERE yr = 1950
  2. SELECT winner
    FROM nobel
    WHERE yr = 1962
    AND subject = 'Literature'
  3. select yr, subject from nobel where winner = 'Albert Einstein';
  4. select winner from nobel where yr >= 2000 AND subject = 'Peace';
  5. select * from nobel where subject = 'Literature' AND yr between 1980 AND 1989;

    between A AND B 는 A와 B를 포함함

  6. SELECT * FROM nobel
    where
    winner IN ('Theodore Roosevelt',
                   'Woodrow Wilson',
                   'Jimmy Carter',
                   'Barack Obama')

    IN 연산자로 winner가 해당 소괄호 내에 존재하면 참

7.

select winner from nobel where winner like 'John%';

혹은

select winner from nobel where LEFT(winner, 4) = 'John';
  1. select yr, subject, winner from nobel 
    where 
    (subject = 'Physics' AND yr = 1980)
    OR (subject = 'Chemistry' AND yr = 1984)
  2. select yr, subject, winner from nobel 
    where 
    yr = 1980 AND subject NOT IN ('Chemistry', 'Medicine');

    NOT IN은 포함하지 않으면 참

  3. select * from nobel
    where (subject = 'Medicine' AND yr < 1910)
    OR (subject = 'Literature' AND yr >= 2004);
  4. select * from nobel where winner = 'PETER GRÜNBERG';
  5. select * from nobel where winner = 'EUGENE O''NEILL';

    EUGENE O'NEILL 문자열은 내부에 '가 존재한다. 이럴경우 ' 앞에 '를 하나 더붙여서 출력

  6. select winner, yr, subject from nobel where winner like 'Sir%'
    ORDER BY yr DESC, winner ASC;

    ORDER BY 의 DESC 는 내림차순, ASC 는 오름차순

14.

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

Physics, Chemistry의 subject필드값이 있는 레코드는 마지막에 나오도록 정렬해야함.
그러므로 ORDER BY가장 첫번째 우선순위를 subject IN ('Physics', 'Chemistry')를 주었다.
IN (~, ~) 연산자는 소괄호내에 포함하면 1 그렇지 않으면 0을 반환한다. 이를 이용해서 정렬을 한 것이다.
ORDER BY절에서 CASE WHEN THEN절을 이용해서 정렬할수도있다. 이는 위 방법보다 직관적이다.

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

quiz

  1. 5

  2. 3

  3. 2
    subquery문제, amount of years를 조회해야하므로 COUNT 집계함수를 이용, Medicine subject를 받지않은 년도를 구해야함.

    SELECT DISTINCT yr from nobel where subject = 'Medicine'

    위 쿼리는 Medicine subject가 존재하는 yr를 조회한뒤 NOT IN으로 포함하지않는 yr를 조회한다.
    그리고 중복을 제거하기위해 DISTINCT를 이용해서 COUNT를 한다.

  4. 3

  5. 3
    이문제 또한 서브쿼리이용

  6. 3
    OR로 줄일수있음

    SELECT DISTINCT yr
    from nobel
    where subject = 'Medicine'
     AND yr NOT IN (SELECT yr from nobel where subject = 'Literature' OR subject = 'Peace');
  7. 4
    주어진 테이블의 레코드 수의 합이 6임.

728x90

'sql' 카테고리의 다른 글

sqlzoo - SUM and COUNT  (0) 2021.07.23
sqlzoo - SELECT in SELECT  (0) 2021.07.17
sqlzoo - SELECT from World  (0) 2021.07.15
sqlzoo - SELECT basics  (0) 2021.07.14