Coding/SQL
[LeetCode-SQL 50] 585. Investments in 2016
kangplay
2025. 3. 3. 19:12
문제
https://leetcode.com/problems/investments-in-2016

설명
Insurance 행 중, 다른 Insurance 행과 lan, lon이 겹치지 않고(고유하고), 다른 Insurance 행 중 하나랑이라도 tiv_2015 값이 동일한, Insurance 데이터의 tic_2016 합을 구하는 문제이다.
각 조건에 대해 서브쿼리를 생성하고, 각 서브쿼리 결과로 나오는 테이블의 pid 에 포함되어있는지, 안되어있는지 판단하면 된다.
단, with as로 선언한 서브쿼리에 대해 바로 not in, in 메서드를 할 수 없으므로, 따로 서브쿼리 형태로 만들어줘야한다!
구현
# Write your MySQL query statement below
with EQUAL_LAN_LON as
(
select distinct I1.pid as pid
from Insurance I1
join Insurance I2 on I1.pid <> I2.pid
where I1.lat = I2.lat and I1.lon = I2.lon
) ,
EQUAL_TIV_2015 as
(
select distinct I1.pid as pid
from Insurance I1
join Insurance I2 on I1.pid <> I2.pid
where I1.tiv_2015 = I2.tiv_2015
)
select round(sum(tiv_2016),2) as tiv_2016
from Insurance i
where i.pid not in (select pid from EQUAL_LAN_LON)
and i.pid in (select pid from EQUAL_TIV_2015);