【力扣白嫖日记】585.2016年的投资-我那不值一提的想法:

时间:2024-03-07 17:37:34
  • 首先梳理表内容,题干只给了一张保险表,记录了投保编号,投保人2015年的总投保金额,2016年的总投保金额,投保人所在城市的维度和经度

  • 其次分析需求,需要求满足以下条件投保金额之和

  • 1.在2015年的投保额至少跟一个其他投保人在2015年的投保额相同

    • 在这个地方就有两个思路:
      • a.通过自连接,然后判断条件pid相同,tiv_2015不同
      • b.通过子查询查询临时表。建立一个临时表,这个临时表对tiv_2015进行分组,只要tiv_2015的数量大于1,就证明至少有一个是相等的。
  • 2.他所在的城市必须与其他投保人都不同
    通过子查询,对lat,lon进行分组,使得lat和lon的数量等于1,这样就可以保证
    查询结果的经纬度不重复

  • 思路一

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(lat) = 1 and count(lon) = 1
)
  • 思路二
select round(sum(distinct i1.tiv_2016),2) as tiv_2016
from Insurance i1 ,Insurance i2
where i1.pid != i2.pid 
and i1.tiv_2015 = i2.tiv_2015
and (i1.lat,i1.lon)
in
(
    select lat,lon
    from Insurance
    group by lat,lon
    having count(lat) = 1 and count(lon) = 1
)