Investments in 2016

medium database sql

Problem

Insurance(pid, tiv_2015, tiv_2016, lat, lon). Sum tiv_2016 where tiv_2015 is shared with at least one other policyholder and (lat, lon) is unique.

Inputins=[(1,10,5,10,10),(2,20,20,20,20),(3,10,30,20,20),(4,10,40,40,0)]
Output45
Rows 1 and 4 share tiv_2015=10 and have unique (lat,lon). Sum = 5 + 40.

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)
  AND (lat, lon) IN (SELECT lat, lon FROM Insurance GROUP BY lat, lon HAVING COUNT(*) = 1);
Time: O(n) Space: O(n)