数据-R语言-图表-决策-Linux-PythonPL/SQL转载部分

SQL函数汇总

2019-03-04  本文已影响35人  apricoter

查询

select * from table
where  A #单个条件
where  A and B #和
where  A or B  #或
where  (A and B) or (C and D)  #优先级
where  in (" "," “," ”)  #多个文本
where  A> 、>=、< 、<=、!=10000  #单个数值
where A between 10000 and 20000 #区间数值
where A like ‘%B%’  #模糊查询
where A not in、not like、not null  #否定

分组

select * from table
group by A  #将数据按组/维度划分
select * from table
group by A ,B #将数据按多维形式聚合
select A,count from table
group by A  #统计数量

除了count,还有max,min,sum,avg等函数,也叫做聚合函数

select A,count(distinct Id) from table
group by A #按A分组(不重复)
select if(A like ‘%B%’,1,0) from table  #逻辑判断

想统计各个城市中有多少数据分析职位,其中,电商领域的职位有多少,在其中的占比

select city,
count(distinct Id),
count(distinct(if(industryField like ‘%电子商务%’,Id,null)))
from table
group by city  #占比,count函数对0,1都计数,因此用null

第一列数字是职位总数,第二列是电商领域的职位数,相除就是占比

想找出各个城市,数据分析师岗位数量在500以上的城市有哪些

第一种,是使用having语句,它对聚合后的数据结果进行过滤。

select city,count(distinct Id) from table
group by city 
having count(distinct Id) >= 500

第二种,是利用嵌套子查询。

select * from (
    select city,count(distinct Id) as counts from table
    group by city ) as table1
where counts >= 500

排序

select * from table
group by A  
order by B  #将数据升序
select * from table
group by A  
order by B desc  #将数据降序

时间

select now()  #当前的系统时间,精确到秒
select date(now())   #当前日期

week函数获得当前第几周,month函数获得当前第几个月。其余还包括,quarter,year,day,hour,minute

时间加减法

select date_add(date(now()) ,interval 1 day)

改变1为负数,达到减法的目的

求两个时间的间隔

datediff(date1,date2)或者timediff(time1,time2)

通过salary计算数据分析师的工资
首先利用locate函数查找第一个k所在的位置。

select locate(“k”,salary),salary from table

然后使用left函数截取薪水的下限。

select left(salary,locate(“k”,salary)-1),salary from DataAnalyst

为了获得薪水的上限,要用substr函数,或者mid,两者等价。

substr(字符串,从哪里开始截,截取的长度)

薪水上限的开始位置是「-」位置往后推一位。截取长度是整个字符串减去「-」所在位置,刚好是后半段我们需要的内容,不过这个内容是包含「K」的,所以最后结果还得再减去1。

select left(salary,locate("k",salary)-1) as bottomsalary,
       substr(salary,locate("-",salary)+1,length(salary)-locate("-",salary)-1) as topsalary,
       salary from table
where salary not like "%以上%"

然后计算不同城市不同工作年限的平均薪资。

select city,workyear,avg((bottomsalary+topsalary)/2) as avgsalary from(
      select left(salary,locate("k",salary)-1) as bottomsalary,
            substr(salary,locate("-",salary)+1,length(salary)-locate("-",salary)-1) as topsalary,
            city,Id,workyear from table
       where salary not like "%以上%") as table1
group by city,workyear
order by city,avgsalary

查询出哪家公司招聘的岗位数最多
查询出O2O、电子商务、互联网金融这三个行业,哪个行业的平均薪资最高;
查询出各城市的最高薪水Top3是哪家公司哪个岗位。

JOIN


A Full Join B = A Left Join B + A Right Join B – A Inner Join B

上一篇下一篇

猜你喜欢

热点阅读