[Inflearn] SQL 강의 고급 -Join 문제들

🌹Haeri Lee·2022년 8월 6일
0

[MySql] 인프런 강의

목록 보기
4/9
post-custom-banner

[1] Hacker Rank 문제 - The Report

*) 출처 https://www.hackerrank.com/challenges/the-report/problem?h_r=internal-search

[문제]

  1. Ketty doesn't want the NAMES of those students who received a grade lower than 8
  2. The report must be in descending order by grade -- i.e. higher grades are entered first.
  3. If there is more than one student with the same grade (8-10) assigned to them, order those particular students by their name alphabetically
  4. if the grade is lower than 8, use "NULL" as their name and list them by their grades in descending order.
  5. If there is more than one student with the same grade (1-7) assigned to them, order those particular students by their marks in ascending order.

[문제풀이]

SELECT CASE WHEN G.GRADE < 8 THEN NULL ELSE S.NAME END AS NAME, 
        G.GRADE,
        S.MARKS
FROM STUDENTS AS S
    INNER JOIN GRADES AS G ON S.MARKS BETWEEN G.MIN_MARK AND G.MAX_MARK
ORDER BY G.GRADE DESC, NAME , S.MARKS

[2] Leetcode 문제 - 180.Consecutive Numbers

*) 출처 : https://leetcode.com/problems/consecutive-numbers/

[문제]

Input: 
Logs table:
+----+-----+
| id | num |
+----+-----+
| 1  | 1   |
| 2  | 1   |
| 3  | 1   |
| 4  | 2   |
| 5  | 1   |
| 6  | 2   |
| 7  | 2   |
+----+-----+
Output: 
+-----------------+
| ConsecutiveNums |
+-----------------+
| 1               |
+-----------------+
Explanation: 1 is the only number that appears consecutively for at least three times.

[문제풀이]


[내가 작성한 정답]
SELECT DISTINCT L.NUM as ConsecutiveNums
FROM LOGS L
	INNER JOIN LOGS L2 ON L.ID = L2.ID
	INNER JOIN LOGS L3 ON L.ID = L3.ID
WHERE L.NUM = L2.NUM = L3.NUM

[강의 답]
SELECT DISTINCT L.NUM AS consecutiveNUMS
FROM Logs AS L
    INNER JOIN Logs AS L_NEXT ON L.ID+1 = L_NEXT.ID
    INNER JOIN Logs AS L_NEXT2 ON L.ID+2 = L_NEXT2.ID
WHERE L.NUM = L_NEXT.NUM AND L.NUM =L_NEXT2.NUM
profile
안녕하세요 공부한 내용을 기록하기 위해서 시작했습니다.
post-custom-banner

0개의 댓글