SQL快速入门_代码汇总

目录

基础查询

查询单列

查询多列

查询所有列

查询结果去重

查询结果限制返回行数

查询后的列重命名

条件查询

基础排序

单列排序(升序降序)

多列排序

操作符(检索满足特定条件的数据)

where语句

基础操作符

高级操作符

操作符混合应用优先级

like操作符(模糊匹配)

高级查询

计算函数

分组查询

分组计算

group by 函数

分组过滤

having语句

分组排序

执行顺序

多表查询

子查询(subquery)

链接查询

左外链接

右外链接

内连接

组合查询(并union或复合查询compound query)

-union

-union all

常用函数

条件函数

if函数

case when

日期函数

时间戳-日期格式转换

年月日截取

日期差计算

文本函数

length--长度

concat--连接

substring_index--分割

instr--定位

substring--截取

窗口函数


基础查询

查询单列

Select device_id
from user_profile

查询多列

Select device_id,gender
from user_profile

查询所有列

Select *
from user_profile

查询结果去重

select distinct age
from user_profile

查询结果限制返回行数

select device_id
from user_profile
limit 5

查询后的列重命名

select device_id as active_user
--select device_id active user
from user_profile 

条件查询

基础排序

单列排序(升序降序)

如果不排序,数据一般按照在底层表中出现的顺序显示;

--升序排序
select age
from user_profile
order by age 
--降序排序
select age
from user_profile
order by age desc

多列排序

<order by a,b,c>将会按照a为最高优先级,依次升序排列;意味着只有在a出现重复值时,才会使用b进行排序。

同时若要多列排序的降序时,desc只应用到位于其前面的列名;意味着若要对abc列名均按照降序排序,应该为<order by a desc,b desc,c desc>

--多列升序排列
select age, gpa
from user_profile
order by age, gpa

--多列降序排列
select age, gpa
from user_profile
order by age desc, gpa desc

操作符(检索满足特定条件的数据)

where语句

where语句一般跟在from语句后

基础操作符

空值 Null

非空值 Not Null

不等于号  <>  or ! =

大于号 >

小于号 <

范围值 between n1 and n2

  •  n1< n2, 否则查询会返回空结果
  •  hivesql 中结果会包括n1,n2两端值
select age, gender
from user_profile

where gender = "male"--筛选男性
--或者说不等于女性
--where gender <> "female" 
--where gender != "female"

where gender is not null --筛选空值


where age < 25 --年龄小于25
where age between 18 and 25 --筛选年龄范围

高级操作符

and 同时满足多个条件

or  只满足多个条件中的一个

in和not in 指定条件范围

操作符混合应用优先级

and 优先级大于 or: 因此若要优先处理or,应该使用括号

--操作符优先级示例

--输出结果为北京大学gpa在3.5以上的学生和山东大学学生
select device_id,gender,age,university,gpa
from user_profile
where university = "北京大学" or gpa>3.5 and university = "山东大学"

--输出结果为北京大学学生和山东大学gpa在3.5以上的学生
select device_id,gender,age,university,gpa
from user_profile
where university = "北京大学" or (gpa>3.5 and university = "山东大学")

like操作符(模糊匹配)

like操作符需要和通配符结合使用,一般使用%;

%表示任何字符出现任意次数

#查询大学名称为北京为开头的大学
select university
from user_profile
where university like "北京%"


#查询大学名称中有北京字段的大学
select university
from user_profile
where university like "%北京%"

高级查询

计算函数

avg 平均值函数

count 计数函数

max 最大值

min 最小值

sum 求和

round 取整

--平均值
select 
avg(gpa) as avg_gpa
from user_profile

--计数
select 
count(*) as num
  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bbllbgs

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值