数据分析学习第一周 NO.2 SQL与MYSQL进阶

第二天:
课程内容:SQL与MYSQL进阶

分组计算:
group by
having 是分组后过滤,where是分组前过滤 用法相同

子查询:
嵌套在其他查询中查询
用法:1 子查询在where里面做过滤 (也可以做表直接使用)2 作为计算字段使用
1

select district from world.city where disrtict in
(select countrycode from world.city where population >= 100000)
或
select a.district from (select district ,countrycode from world.city) a;

2

select id,name,countrycode,(select name from world.city where world.country.code=world.city.countrycode) as b;

连接表:
inner join 取交集
left join 左边是主表,共有部分选取出来,然后主表的都选取出来
right join 相反
一次只能针对两张表join,

outjoin : 目前个人理解,交集取1份,然后两边没有的也要选出来。

组合查询:
union 规则:
必须由两条或者两条以上的select语句组成,语句之间用union分隔
union中的每个查询必须包含相同的列,表达式或聚集函数
列数据类型必须兼容
union 会自动去重,不需要使用 union all
工作中: 速度快
EX:

select 	countrycode,sum(population) from world.city group by countrycode  
union 
select code,population from world.county
union

union可以多个使用
order by 只能用在最后的语句
数值可以变成字符,字符不能变成数值。

表的创建和操作:
存表的时候,不允许有相同的列名
EX: create table if not exists world.XXX
AS 下面跟代码

删除表:drop table if exists XXX

创建一个表:(一般就不做修改了,因为删除丢掉是不可逆的)
创建一个表 create table XXX
定义列名数据类型,设置主键(ps.主键可以是多个组合,也可以不用主键)(
name char
primary key (id)

插入数据
insert into
select
from

更新和删除表:(建议创建表的时候就考虑好表结构,MYsql 不可逆)
alter 修改
EX:
alter table world.country modify column population bigint 把表中population数据类型变成bigint
alter更改是创建一个新的一行,然后往里面填数据

alter table world.test
add new_name char(80);

alter table world.test
drop id   删除了id这一行

update,delete 不可逆,最好结合where,要不就是对所有的行操作了!

update world.test
set population=0 
where
id=129

update world.test
set new_name=1
where new_name is null

delete  from world.test
where new_name is null

drop 是删除表,delete是删除记录但是表还在

null值既不是空值也不是0 所以使用 is null 和is not null
null会被忽略计算

创建表的时候可以在定义数据类型
id int not null

select * from world where name is null 

SQL随堂练习:
数据分析学习第一周 NO.2 SQL与MYSQL进阶

SELECT 性别,sum(历史成功借款金额) 总成功借款金额,sum(历史成功借款次数) 总成功借款次数 
FROM 拍拍贷.LC
group by 性别

结果显示
数据分析学习第一周 NO.2 SQL与MYSQL进阶

select 初始评级,sum(历史逾期还款期数) 总逾期次数 from 拍拍贷.LC
group by 初始评级

数据分析学习第一周 NO.2 SQL与MYSQL进阶