diff --git a/README.md b/README.md index 75fd7a5..46b7ac5 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,7 @@ Have a good contributing! - [184. Department Highest Salary](./leetcode/medium/184.%20Department%20Highest%20Salary.sql) - [550. Game Play Analysis IV](./leetcode/medium/550.%20Game%20Play%20Analysis%20IV.sql) - [570. Managers with at Least 5 Direct Reports](./leetcode/medium/570.%20Managers%20with%20at%20Least%205%20Direct%20Reports.sql) + - [585. Investments in 2016](./leetcode/medium/585.%20Investments%20in%202016.sql) - [602. Friend Requests II: Who Has the Most Friends](./leetcode/medium/602.%20Friend%20Requests%20II:%20Who%20Has%20the%20Most%20Friends.sql) - [626. Exchange Seats](./leetcode/medium/626.%20Exchange%20Seats.sql) - [1045. Customers Who Bought All Products](./leetcode/medium/1045.%20Customers%20Who%20Bought%20All%20Products.sql) diff --git a/leetcode/medium/585. Investments in 2016.sql b/leetcode/medium/585. Investments in 2016.sql new file mode 100644 index 0000000..3ec4061 --- /dev/null +++ b/leetcode/medium/585. Investments in 2016.sql @@ -0,0 +1,45 @@ +/* +Question 585. Investments in 2016 +Link: https://leetcode.com/problems/investments-in-2016/description/?envType=study-plan-v2&envId=top-sql-50 + +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. +*/ + +SELECT ROUND(SUM(i.tiv_2016)::numeric, 2) AS tiv_2016 +FROM Insurance AS i +WHERE (i.lat, i.lon) IN ( + SELECT + i1.lat, + i1.lon + FROM Insurance AS i1 + GROUP BY i1.lat, i1.lon + HAVING COUNT(1) = 1 +) AND i.tiv_2015 IN ( + SELECT i2.tiv_2015 + FROM Insurance AS i2 + GROUP BY i2.tiv_2015 + HAVING COUNT(1) > 1 +)