【SQL】585. 2016年的投资 (group by 执行图解)

前述

知识点学习:看一遍就理解:group by 详解 ,图解讲解细致,推荐学习。

题目描述

leetcode题目:585. 2016年的投资


  1. 定位pid:符合两个条件的。直接用条件筛选即可。指定字段in, not in,再结合group by having等。
  2. 再加和,注意小数点后保留两位 => 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
)

记录自己思维错误点:

  1. 要做筛选,从表中挑选出需要的数据,而不要总想着删除表中多余行。(一开始想的是,如何把两个重复经纬度的去掉? )
  2. 注意:where子句还处于"确定"结果集的过程中,因而不能使用聚集函数。用having过滤即可。
  3. group by 细节学习:看一遍就理解:group by 详解
相关推荐
向上的车轮12 分钟前
Django学习笔记二:数据库操作详解
数据库·django
编程老船长23 分钟前
第26章 Java操作Mongodb实现数据持久化
数据库·后端·mongodb
Mephisto.java23 分钟前
【力扣 | SQL题 | 每日四题】力扣2082, 2084, 2072, 2112, 180
sql·算法·leetcode
丶Darling.26 分钟前
LeetCode Hot100 | Day1 | 二叉树:二叉树的直径
数据结构·c++·学习·算法·leetcode·二叉树
全栈师1 小时前
SQL Server中关于个性化需求批量删除表的做法
数据库·oracle
Data 3171 小时前
Hive数仓操作(十七)
大数据·数据库·数据仓库·hive·hadoop
BergerLee2 小时前
对不经常变动的数据集合添加Redis缓存
数据库·redis·缓存
gorgor在码农2 小时前
Mysql 索引底层数据结构和算法
数据结构·数据库·mysql
一个不知名程序员www2 小时前
leetcode第189题:轮转数组(C语言版)
c语言·leetcode
-seventy-2 小时前
SQL语句 (MySQL)
sql·mysql