目录
基础查询
查询单列
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