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:
- have the same tiv_2015 value as one or more other policyholders, and
- 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.
# 쿼리를 작성하는 목표, 확인할 지표 : tiv_2015값이 같으면 tiv_2016을 합한다. tiv_2015의 lat,lon은 고유의 값이어야 계산에 포함. / tiv_2015, lat, lon, tiv_2016
# 쿼리 계산 방법 : 1. 같은 tiv_2015 값을 갖고 있는 경우 추출 -> 2. (lat, lon)이 고유한 값인 경우만 추출 -> 3. tiv_2016의 총합 계산
# 데이터의 기간 : x
# 사용할 테이블 : insurance
# JOIN KEY : x
# 데이터 특징 : x
SELECT
# 3
ROUND(SUM(tiv_2016), 2) AS tiv_2016
FROM insurance
WHERE
# 1
tiv_2015 IN (SELECT tiv_2015 FROM insurance GROUP BY tiv_2015 HAVING COUNT(*) > 1) AND
# 2
(lat, lon) IN (SELECT lat, lon FROM insurance GROUP BY lat, lon HAVING COUNT(*) = 1)
'[SQL]' 카테고리의 다른 글
LeetCode 코딩 테스트 - Consecutive Numbers(LV.Medium) (0) | 2025.03.18 |
---|---|
LeetCode 코딩 테스트 - Managers with at Least 5 Direct Reports(LV.Medium) (0) | 2025.03.17 |
LeetCode 코딩 테스트 - Immediate Food Delivery II(LV.Medium) (0) | 2025.03.15 |
LeetCode 코딩 테스트 - Department Highest Salary(LV.Medium) (0) | 2025.03.15 |
LeetCode 코딩 테스트 - Restaurant Growth(LV.Medium) (0) | 2025.03.13 |