SQL/문제풀이 50

[LeetCode] investments-in-2016 📌

https://leetcode.com/problems/investments-in-2016/description/?envType=study-plan-v2&envId=top-sql-50 1. tiv_2015가 중복 2. lat, lon이 유일 2가지 조건을 WHERE절 서브쿼리를 이용해 작성해주면 된다 SELECT ROUND(SUM(tiv_2016), 2) AS tiv_2016 FROM insurance WHERE tiv_2015 IN ( SELECT tiv_2015 FROM insurance GROUP BY tiv_2015 HAVING COUNT(*) > 1 -- 해당 tiv_2015가 2번 이상 등장해야 함 ) AND WHERE lat, lon IN ( SELECT lat, lon FROM insuran..

SQL/문제풀이 2024.03.26

[LeetCode] exchange-seats 📌

https://leetcode.com/problems/exchange-seats/?envType=study-plan-v2&envId=top-sql-50 SELECT a.id, CASE WHEN a.id % 2 = 1 THEN b.student ELSE c.student END AS student FROM seat a LEFT JOIN seat b ON a.id + 1 = b.id LEFT JOIN seat c ON a.id = c.id + 1 id가 홀수인 경우와 짝수인 경우를 나눠서 문제를 해결하려고 했는데 table의 마지막 열에 대해서 어떻게 처리가 안되더라 .. 원래 table은 다음과 같다. SELECT CASE WHEN id = (SELECT MAX(id) FROM seat) AND id % ..

SQL/문제풀이 2024.03.20

[LeetCode] last-person-to-fit-in-the-bus 📌

https://leetcode.com/problems/last-person-to-fit-in-the-bus/?envType=study-plan-v2&envId=top-sql-50 누적합을 어떻게 구해야하는지 몰라서 문제에 접근을 못했다! 1. JOIN 이용 SELECT * FROM Queue a JOIN Queue b ON a.turn >= b.turn ORDER BY a.turn, b.turn ex) a의 turn이 2 --> turn이 1, 2인 row가 JOIN 됨 2. a.turn으로 GROUP BY 후 해당 순서의 누적 weight를 구하기 위해 SUM(b.weight)를 계산 HAVING절에 1000 이하라는 조건을 걸어주고 누적 weight가 가장 큰 순서대로 정렬한다 이때 a.person_..

SQL/문제풀이 2024.03.20