前述
知识点学习:看一遍就理解:group by 详解 ,图解讲解细致,推荐学习。
题目描述
leetcode题目:585. 2016年的投资
- 定位pid:符合两个条件的。直接用条件筛选即可。指定字段in, not in,再结合group by having等。
- 再加和,注意小数点后保留两位 => ROUND()函数
写法一
sql
select round(sum(A.tiv_2016), 2) as tiv_2016
from Insurance A
where A.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
)
写法二
不同点:官方题解中用了concat()函数,不用也行
sql
select round(sum(A.tiv_2016), 2) as tiv_2016
from Insurance A
where A.tiv_2015 in (
select tiv_2015
from Insurance
group by tiv_2015
having count(*) > 1
)
and concat(lat, lon) in(
select concat(lat, lon)
from Insurance
group by lat, lon
having count(*) = 1
)
记录自己思维错误点:
- 要做筛选,从表中挑选出需要的数据,而不要总想着删除表中多余行。(一开始想的是,如何把两个重复经纬度的去掉? )
- 注意:where子句还处于"确定"结果集的过程中,因而不能使用聚集函数。用having过滤即可。
- group by 细节学习:看一遍就理解:group by 详解。