KEEP GOING

[MySQL] 1주차 본문

code review/sql

[MySQL] 1주차

jmHan 2022. 2. 28. 11:40
반응형

[순위 구하기]

https://leetcode.com/problems/rank-scores/submissions/

 

Rank Scores - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

1. rank : 동일한 값은 동일한 순위 부여

   * 직업별로 순위를 매기고 싶은 경우) RANK() OVER (PARTITION BY JOB ORDER BY SAL DESC)

SELECT score
      ,RANK() OVER(ORDER BY score DESC)as 'rank'
FROM 테이블
score rank
90 1
80 2
80 2
72 4

 

2. dense_rank : 동일한 값은 하나로 인식

SELECT score
      ,DENSE_RANK() OVER(ORDER BY score DESC)as 'rank'
FROM 테이블
score rank
90 1
80 2
80 2
72 3

 

3. row_number : 동일한 값일지라도 고유한 순위 부여 

SELECT score
      ,ROW_NUMBER() OVER(ORDER BY score DESC)as 'rank'
FROM 테이블
score rank
90 1
80 2
80 3
72 4

 

[두 날짜의 차이 가져오기]

https://leetcode.com/problems/rising-temperature/

 

Rising Temperature - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

[정답 코드 : join 사용]

SELECT w1.id
FROM Weather w1 INNER JOIN Weather w2 
     ON DATEDIFF(w1.recordDate, w2.recordDate) = 1
WHERE w1.temperature > w2.temperature;

-datediff(구분자, 시작일, 종료일) : 차이를 구분할 두 날짜를 시작일과 종료일에 대입하고 구분자에 연도, 월, 일을 적는다.

ex) 렌트한지 60일이 지난 주문 번호 조회하기

      시간 연장이 필요한 좌석 정보 확인하기 

      일주일 전 비가 내린 날짜 확인하기   

SELECT w1.id
FROM Weather w1 INNER JOIN Weather w2 
     ON DATE_SUB(w1.recordDate, INTERVAL 1 DAY) = w2.recordDate
WHERE w1.temperature > w2.temperature;

-date_sub(기준날짜, interval) : 기준 날짜에 입력한 기간만큼 빼는 함수 

 

[정답 코드: 서브쿼리 사용]

SELECT id
FROM Weather w1 
WHERE temperature > ( SELECT temperature
                      FROM Weather w2
                      WHERE DATEDIFF(w1.recordDate, w2.recordDate) = 1 
                     )

 

 

* 알아두면 좋을 자료 

- from절 서브쿼리로 임시 테이블을 생성할 경우 반드시 테이블명을 설정해야 한다.

  그렇지 않으면 error 발생 

Every derived table must have its own alias

 

- LAG(컬럼명1) OVER(ORDER BY 컬럼명2) : 컬럼명2를 정렬한 기준으로 컬럼명1을 한칸씩 뒤로 미룬다.

- LEAD(컬럼명1) OVER(ORDER BY 컬럼명2) : 컬럼명2를 정렬한 기준으로 컬럼명1을 한칸씩 앞으로 당긴다.

 

[CASE 문으로 1개의 컬럼 분리하기]

https://leetcode.com/problems/reformat-department-table/

 

Reformat Department Table - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

[정답 코드]

SELECT id
      ,SUM(CASE WHEN month = 'Jan' THEN revenue ELSE NULL END) AS 'Jan_Revenue'
      ,SUM(CASE WHEN month = 'Feb' THEN revenue ELSE NULL END) AS 'Feb_Revenue'
      ,SUM(CASE WHEN month = 'Mar' THEN revenue ELSE NULL END) AS 'Mar_Revenue'
      ,SUM(CASE WHEN month = 'Apr' THEN revenue ELSE NULL END) AS 'Apr_Revenue'
      ,SUM(CASE WHEN month = 'May' THEN revenue ELSE NULL END) AS 'May_Revenue'
      ,SUM(CASE WHEN month = 'Jun' THEN revenue ELSE NULL END) AS 'Jun_Revenue'
      ,SUM(CASE WHEN month = 'Jul' THEN revenue ELSE NULL END) AS 'Jul_Revenue'
      ,SUM(CASE WHEN month = 'Aug' THEN revenue ELSE NULL END) AS 'Aug_Revenue'
      ,SUM(CASE WHEN month = 'Sep' THEN revenue ELSE NULL END) AS 'Sep_Revenue'
      ,SUM(CASE WHEN month = 'Oct' THEN revenue ELSE NULL END) AS 'Oct_Revenue'
      ,SUM(CASE WHEN month = 'Nov' THEN revenue ELSE NULL END) AS 'Nov_Revenue'
      ,SUM(CASE WHEN month = 'Dec' THEN revenue ELSE NULL END) AS 'Dec_Revenue' 
FROM Department
GROUP BY id
ORDER BY id

- SELECT 쿼리 동작 순서

1. FROM (조회할 테이블 확인)

2. ON

3. JOIN

4.. WHERE (데이터 추출 조건 확인)

5. GROUP BY (컬럼 그룹화)

6. ROLLUP | CUBE

7. HAVING (그룹화 조건)

8. SELECT (데이터 추출)

9. DISTINCT

10. ORDER BY (데이터 순서 정렬)

11. TOP

 

- SUM() 사용시 NULL 처리 ) IFNULL(SUM(컬럼명), 0)

                                          IF(SUM(컬럼명) IS NULL, 0, SUM(컬럼명))

 

반응형

'code review > sql' 카테고리의 다른 글

[MySQL] 3주차 (for coding test)  (0) 2022.03.07
[MySQL] 2주차  (0) 2022.03.06
[MySQL] LeetCode : Nth highest Salary  (0) 2022.02.18
[MySQL] 정규 표현식 정리(REGEXP)  (0) 2022.02.09
[MySQL] LeetCode : Consecutive-Numbers  (0) 2022.02.07
Comments