ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • leetcode - 585. Investments in 2016
    SQL 문제풀이 2022. 7. 4. 16:50

    난이도 : Medium

     

    Table: Insurance

    +-------------+-------+
    | Column Name | Type  |
    +-------------+-------+
    | pid         | int   |
    | tiv_2015    | float |
    | tiv_2016    | float |
    | lat         | float |
    | lon         | float |
    +-------------+-------+
    pid is the primary key column 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.
    lon is the longitude of the policy holder's city.
    

     

    Write an SQL query 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 like any other policyholder (i.e., the (lat, lon) attribute pairs must be unique).

    Round tiv_2016 to two decimal places.

     

     

    where절 서브쿼리를 활용한 방법 1
    SELECT ROUND(SUM(tiv_2016), 2) tiv_2016
    FROM Insurance
    WHERE tiv_2015 IN (
                       SELECT tiv_2015
                       FROM Insurance
                       GROUP BY tiv_2015
                       HAVING COUNT(*) >= 2
                       )
    AND (lat, lon) IN (
                       SELECT lat
                            , lon
                       FROM Insurance
                       GROUP BY lat, lon
                       HAVING COUNT(*) = 1
                       )

    Accepted (88.61%)

     

     

    윈도우 함수를 활용한 방법
    SELECT ROUND(SUM(tiv_2016), 2) tiv_2016
    FROM (
          SELECT tiv_2016
               , COUNT(*) OVER (PARTITION BY tiv_2015) cnt1
               , COUNT(*) OVER (PARTITION BY lat, lon) cnt2
          FROM insurance
          ) sub
    WHERE cnt1 >= 2 
    AND cnt2 = 1

    Accepted (92.91%)

     

     

    where절 서브쿼리를 활용한 방법 2 (exists 사용)
    SELECT ROUND(SUM(tiv_2016), 2) tiv_2016
    FROM Insurance t1
    WHERE EXISTS (
                  SELECT *
                  FROM Insurance
                  WHERE pid <> t1.pid
                  AND tiv_2015 = t1.tiv_2015
                  )
    AND NOT EXISTS (
                    SELECT *
                    FROM Insurance 
                    WHERE pid <> t1.pid
                    AND (lat, lon) = (t1.lat,t1.lon)
                    )

    Accepted (93.40%)

Designed by Tistory.