charlly
- 常用函数
-- 数学函数
-- 练习:查询各部门员工人数占比(保留两位小数)
select deptno,count(*) as 部门人数, round(count(*)/(select count(*) from emp),2) as 人数占比
from emp  
group by deptno;


-- 字符串函数
-- 练习:查询各部门员工人数占比(以百分比显示)
select deptno,count(*) as 部门人数, concat(round((count(*)/(select count(*) from emp))*100,2),"%") as 人数占比
from emp  
group by deptno;-- concat函数输出的是文本,在后续数据处理中 很难使用,因此在实际工作中一般是输出数值型,在EXCEL或者powerbi等可视化里面进行显示方式的改修,修改完之后还是数值型


-- 日期函数
-- 练习:查询每位员工的工龄(年):ename,hiredate,工龄
select ename,hiredate,timestampdiff(year,hiredate,curdate()) as 工龄 from emp;


-- 分组合并函数
-- 练习:查询各部门的员工姓名
-- GROUP_CANCAT([distinct] str [order by str asc/desc] [separator])
select 
deptno,
group_concat(distinct ename order by sal desc separator \'/\')--   不写分隔符情况下默认是\',\'作为分隔符
from emp group by deptno;



-- 逻辑函数
-- ifnull函数:查询每位员工的实发工资(基本工资+提成,没有提成计为0)

select 
ename, sal,comm,
sal+ifnull(comm,0) as 实发工资
from emp;


-- if函数:查询每位员工的工资级别:3000及以上为高,1500-3000为中,1500及以下为低
select * from emp;
select 
* ,
if(sal>3000,\'\',if(sal<=1500,\'\',\'\')) as 工资级别
from emp;

-- 逻辑表达式 case when ...then... else ... end
select *,
case when sal>3000 then \'\'
     when sal<=1500 then \'\'
     else \'\'
     end as 工资级别
from emp;

 

分类:

技术点:

相关文章: