阅读量:0
数据库字段:
实现业务:
1)查询对应部门,年份的员工季度评价信息:
对应sql语句:
使用 group by 和 GROUP_CONCAT 关键字进行行转列,
case when 后接关联条件,如果不写默认查询该emp_name对应的所有的level_name数据
CASE WHEN eval_quarter = 1 THEN level_name else "未查到" END,如果后接else关键字,表示没有查到level_name数据时使用默认值"未查到",但是有点问题,"未查到"会替换查到的level_name数据,干脆不用。
SELECT e.emp_name, GROUP_CONCAT(CASE WHEN eval_quarter = 1 THEN level_name END) AS p1, GROUP_CONCAT(CASE WHEN eval_quarter = 2 THEN level_name END) AS p2, GROUP_CONCAT(CASE WHEN eval_quarter = 3 THEN level_name END) AS p3, GROUP_CONCAT(CASE WHEN eval_quarter = 4 THEN level_name END) AS p4 FROM kf_emp e left join kf_eval l on e.emp_id = l.eval_emp_id left join kf_dept d on e.emp_dept_id = d.dept_id left join kf_level le on le.level_id = l.eval_level_id and l.eval_year = 2023 and d.dept_id = 1 GROUP BY l.eval_emp_id,e.emp_name;
2)对应部门,年份的员工季度评价功能:
对应sql语句:
and条件写在左连接表后而不是where条件后。两种情况还是有区别的:
写在where后会直接筛选主表kf_emp数据
写在left join 后会筛选kf_eval表数据,但是主表不动。
select * from kf_emp e left join kf_eval el on el.eval_emp_id = e.emp_id and eval_quarter = 1 left join kf_level le on le.level_id = el.eval_level_id and eval_year = 2023 where emp_dept_id= 1