中国统计网 | 新手速进!,SQL大厂面试常考知识点( 二 )


中国统计网 | 新手速进!,SQL大厂面试常考知识点
文章图片
1.去重distinct
--罗列不同的idselectdistinctidfromtable_1--统计不同的id的个数selectcount(distinctid)fromtable_1--优化版本的countdistinctselectcount(*)from(selectdistinctidfromtable_1)tbdistinct会对结果集去重 , 对全部选择字段进行去重 , 并不能针对其中部分字段进行去重 。 使用countdistinct进行去重统计会将reducer数量强制限定为1 , 而影响效率 , 因此适合改写为子查询 。
2.聚合函数和groupby
--统计不同性别(F、M)中 , 不同的id个数groupbysex--其它的聚合函数例如:max/min/avg/sum--统计最大/最小/平均年龄selectmax(age),min(age),avg(age)fromtable_1groupbyid聚合函数帮助我们进行基本的数据统计 , 例如计算最大值、最小值、平均值、总数、求和 。
3.筛选where/having
--统计A公司的男女人数wherecompany='A'--统计各公司的男性平均年龄 , 并且仅保留平均年龄30岁以上的公司selectcompany,avg(age)fromtable_1wheresex='M'groupbycompanyhavingavg(age)>30;4.排序orderby
--按年龄全局倒序排序取最年迈的10个人selectid,agefromtable_1orderbyageDESClimit105.casewhen条件函数
--收入区间分组selectid,(casewhenCAST(salaryasfloat)<50000Then'0-5万'whenCAST(salaryasfloat)>=50000andCAST(salaryasfloat)<100000then'5-10万'whenCAST(salaryasfloat)>=100000andCAST(salaryasfloat)<200000then'10-20万'whenCAST(salaryasfloat)>200000then'20万以上'elseNULLendfromtable_1;case函数的格式为(casewhen条件1thenvalue1elsenullend),其中else可以省 , 但是end不可以省 。
在这个例子里也穿插了一个CAST的用法 , 它常用于string/int/double型的转换 。
6.字符串
1)concat(A,B...)返回将A和B按顺序连接在一起的字符串 , 如:concat('foo','bar')返回'foobar' 。
selectconcat('www','.iteblog','.com')fromiteblog;2)split(str,regex)用于将string类型数据按regex提取 , 分隔后转换为array 。
--以","为分隔符分割字符串 , 并转化为arraySelectsplit("1,2,3",",")asvalue_arrayfromtable_1;--结合arrayindex,将原始字符串分割为3列selectvalue_array[0],value_array[1],value_array[2]from(selectsplit("1,2,3",",")asvalue_arrayfromtable_1)t3)substr(str,0,len)截取字符串从0位开始的长度为len个字符 。
selectsubstr('abcde',3,2)fromiteblog;--得到cd三.基础进阶
1.row_number
--按照字段salary倒序编号select*,row_numberover(orderbysalarydesc)asrow_numfromtable_1;--按照字段deptid分组后再按照salary倒序编号select*,row_numberover(partitionbydeptidorderbysalarydesc)asrankfromtable_1;
中国统计网 | 新手速进!,SQL大厂面试常考知识点
文章图片
按照depid分组 , 对salary进行排序(倒序)
除了row_number函数之外 , 还有两个分组排序函数 , 分别是rank和dense_rank 。
rank排序相同时会重复 , 总数不会变 , 意思是会出现1、1、3这样的排序结果;
dense_rank排序相同时会重复 , 总数会减少 , 意思是会出现1、1、2这样的排序结果 。
row_number则在排序相同时不重复 , 会根据顺序排序 。
2.percentile百分位函数
--获取income字段的top10%的阈值selectpercentile(CAST(salaryASint),0.9))asincome_top10p_thresholdfromtable_1;--获取income字段的10个百分位点selectpercentile(CAST(salaryASint),array(0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0))asincome_percentilesfromtable_1;3.时间函数


推荐阅读