mysql 문제풀이 30

1978. Employees Whose Manager Left the Company

https://leetcode.com/problems/employees-whose-manager-left-the-company/  Find the IDs of the employees whose salary is strictly less than $30000 and whose manager left the company. When a manager leaves the company, their information is deleted from the Employees table, but the reports still have their manager_id set to the manager that left. 내용 요약:매니저가 퇴사하면, Employess 목록에서 사라지지만, 다른 직원의 매니저로서 기..

1527. Patients With a Condition

https://leetcode.com/problems/patients-with-a-condition/description/ replace, substring, concat, left, right, lower, upper, trim, length, format, instr 정도만 알아도 SQL 데이터 변형에 큰 문제가 없겠지만, Regex 문법 까지 익숙해지면 빠른 전처리에 큰 도움이 될 것 같다.   Write a solution to find the patient_id, patient_name, and conditions of the patients who have Type I Diabetes. Type I Diabetes always starts with DIAB1 prefix.Return the r..

1251. Average Selling Price

https://leetcode.com/problems/average-selling-price/description/ 15번째 케이스에서 Prices 테이블의 product_id가 3이상으로 추가되면서, UnitSold 테이블에 없는 데이터 값도 결과값에 으로 나타나야 했기에 INNER 를 LEFT로 수정하고,조건 결과값으로, Null값도 함께 나타날 수 있도록 WHERE문 끝에 "or UnitsSold.product_id IS NULL" 을 이어붙인 뒤 COALESCE를 ROUND 앞에 씌워 NULL값 처리를 해야했다.   잠깐 생각하게 만들었던 문제다음부턴 예시에 보이지 않는 테스트 케이스를 예상해서 작성해봐야겠다. *** JOIN에 AND 조건을 덧붙이는 방식보다, WHERE로 조건을 추가 작성하는 ..

550. Game Play Analysis IV

https://leetcode.com/problems/game-play-analysis-iv/description/미뤄뒀던 포스팅을 이제야.... 한 20개 더 밀려있다. 기존의 511. Game Play Analysis I 와 유사한 문제최초 접속 후, 다음날 다시 접속한 게임플레이어의 비율을 구하면 된다.  Example 1:Input: Activity table:+-----------+-----------+------------+--------------+| player_id | device_id | event_date | games_played |+-----------+-----------+------------+--------------+| 1 | 2 | 2016-0..

511. Game Play Analysis I

https://leetcode.com/problems/game-play-analysis-i/ 쉬운 문제이지만, 윈도우 함수를 간단히 활용해보기에 좋은 문제 # 플레이어의 최초 로그인 날짜 구하기 1) 기본 풀이 SELECT player_id , MIN(event_date) AS first_login FROM Activity GROUP BY player_id # 플레이어의 최초 로그인 날짜 구하기 2) 윈도우 함수 + WITH 문 활용 WITH login AS ( SELECT ROW_NUMBER() OVER (PARTITION BY player_id ORDER BY event_date) AS player_login , player_id , event_date AS first_login FROM Activi..

Leetcode 601 - Human Traffic of Stadium

링크: https://leetcode.com/problems/human-traffic-of-stadium/ 습득한 점: 연속되는 숫자를 찾는 새로운 아이디어. GROUP BY, PARTITION BY 차이 재확인. hard 난이도는 아니었다. 문제: 사람 수 (people)가 100이상일 때, 3개 이상의 연속되는 "id"값에 대한 행을 모두 조회하는 쿼리 작성 결과값은 "visit_date" 기준으로 오름차순 정렬 문제파악: 일단 visit_date는 정렬 빼고는 신경 쓸 필요는 없을 것 같았고, 우선 사람 수가 100명 이상인 테이블을 걸러낸 결과값을 WITH문으로 테이블을 새롭게 구성한 뒤 쿼리 작성을 시작하면 될 것 같다. 대략적으로 2가지 풀이법이 보인다. 셀프 조인 혹은 윈도우 함수 사용하기 ..

1321. Restaurant Growth

https://leetcode.com/problems/restaurant-growth/description/ WITH문을 2번 중첩하여 문제를 풀이했었고, 내 풀이만 다른 분들과 달랐기에, 해결과정이 기억에 많이 남았던 문제 중 하나였다. 지금은 단순 풀이를 위한 쿼리작성이지만, 나중에는 쿼리 최적화 관점에서도 작성해보면 좋을 것 같다. -> 쿼리 최적화 관련자료 ✅ 쿼리 최적화 첫걸음 — 보다 빠른 쿼리를 위한 7가지 체크 리스트 DB에 대한 데이터 분석가의 에티켓 medium.com 1321. Restaurant Growth -> 이전 6일 ~ 당일 amount 합산 # 방문일별 계산 WITH grouped_visit_on AS ( SELECT visited_on , SUM(amount) AS amo..

180. Consecutive Numbers

https://leetcode.com/problems/consecutive-numbers/description/ 기존에 테이블 조인 방식으로 풀었던 문제이지만, LEAD() 를 활용해서도 풀어볼 수 있었다. 큰 차이는 없지만, 윈도우함수를 활용하는 방법이 조금 더 직관적으로 이해하기 좋았음. id NUM next afternext 1 1 1 1 2 1 1 2 3 1 2 1 4 2 1 2 5 1 2 2 6 2 2 null 7 2 null null 1) 윈도우 함수 풀이: LEAD SELECT DISTINCT l.NUM AS ConsecutiveNums FROM( SELECT NUM , LEAD(NUM,1) OVER (ORDER BY id) AS next , LEAD(NUM,2) OVER (ORDER BY ..

Leetcode 185 - Department Top Three Salaries

https://leetcode.com/problems/department-top-three-salaries/ 습득한 점: 윈도우 함수를 활용할 때, DENSE_RANK() OVER (PARTITION BY departmentid ORDER BY salary DESC) 처럼 PARTITION BY와 ORDER BY를 함께 쓸 수 있다는 점을 알게되었음. + 순위 정하기 함수의 차이점 - ROW_NUMBER(), RANK(), DENSE_RANK() SELECT val , ROW_NUMBER() OVER (ORDER BY val) AS row_number , RANK() OVER (ORDER BY val) AS rank , DENSE_RANK() OVER (ORDER BY val) AS dense_rank ..