Table: Insurance
+-------------+-------+
| Column Name | Type |
+-------------+-------+
| pid | int |
| tiv_2015 | float |
| tiv_2016 | float |
| lat | float |
| lon | float |
+-------------+-------+
pid is the primary key (column with unique values) for this table.
Each row of this table contains information about one policy where:
pid is the policyholder's policy ID.
tiv_2015 is the total investment value in 2015 and tiv_2016 is the total investment value in 2016.
lat is the latitude of the policy holder's city. It's guaranteed that lat is not NULL.
lon is the longitude of the policy holder's city. It's guaranteed that lon is not NULL.
Write a solution to report the sum of all total investment values in 2016 tiv_2016,
for all policyholders who:
1) have the same tiv_2015 value as one or more other policyholders, and
2) are not located in the same city as any other policyholder (i.e., the (lat, lon)
attribute pairs must be unique).
Round tiv_2016 to two decimal places.
The result format is in the following example.
Example 1:
Input:
Insurance table:
+-----+----------+----------+-----+-----+
| pid | tiv_2015 | tiv_2016 | lat | lon |
+-----+----------+----------+-----+-----+
| 1 | 10 | 5 | 10 | 10 |
| 2 | 20 | 20 | 20 | 20 |
| 3 | 10 | 30 | 20 | 20 |
| 4 | 10 | 40 | 40 | 40 |
+-----+----------+----------+-----+-----+
Output:
+----------+
| tiv_2016 |
+----------+
| 45.00 |
+----------+
Explanation:
The first record in the table, like the last record, meets both of the two criteria.
The tiv_2015 value 10 is the same as the third and fourth records, and its location is unique.
The second record does not meet any of the two criteria. Its tiv_2015 is not like any other
policyholders and its location is the same as the third record, which makes the third record fail, too.
So, the result is the sum of tiv_2016 of the first and last record, which is 45.
# 풀이
with tiv as (
select tiv_2015
from Insurance
group by tiv_2015
having count(*)> 1
), loc as (
select lat
, lon
from Insurance
group by lat, lon
having count(*) = 1
)
select round(sum(tiv_2016), 2) as tiv_2016
from Insurance i
left join tiv t
on i.tiv_2015 = t.tiv_2015
left join loc l
on i.lat = l.lat
and i.lon = l.lon
where t.tiv_2015 is not null
and l.lat is not null;
- 해설
1) with문으로 만든 tiv 테이블은 여러 policyholders들에게서 중복으로 나타나는 tiv_2015를 찾는다
2) with문으로 만든 loc 테이블은 unique한 lat과 lon을 찾는다.
3) 위 두 테이블의 결과를 Insurance 테이블과 조인해서 null값이 없는 행을 찾고, 해당 행의 tiv_2016의 합을 구한다.
3-1) loc 테이블을 조인할 때 조건을 lat, lon 둘 다 걸어주어야 한다. 문제에서 the (lat, lon) attribute pairs must be unique
라고 조건을 주었기 때문!
'코딩테스트 > SQL - Leetcode' 카테고리의 다른 글
1158. Market Analysis I (0) | 2024.01.16 |
---|---|
608. Tree Node (0) | 2024.01.12 |
Leetcode SQL Easy난이도 전부 해결! (0) | 2024.01.10 |
1789. Primary Department for Each Employee (2) | 2024.01.08 |
1484. Group Sold Products By The Date (2) | 2023.12.27 |