如何实现员工培训查询结果按员工单行展示
解决员工培训核查查询结果重复行问题
你当前的查询结果出现同一员工多行的原因是:employee_table与course_table关联后,每个员工在course_table中对应多条课程记录,即使使用distinct也无法合并这些行(只有完全重复的行才会被去重)。要实现每个员工一行、多列展示课程完成状态的目标,需要通过分组聚合来处理。
修改后的查询语句
select im.employee_id, im.last_name, im.first_name, max(case when sc.course_code = 'ABC' then 1 else 0 end) as "课程1(ABC)完成情况", max(case when sc.course_code = 'DEF' then 1 else 0 end) as "课程2(DEF)完成情况", max(case when sc.course_code = 'GHI' then 1 else 0 end) as "课程3(GHI)完成情况" from employee_table im join course_table sc on im.employee_id = sc.employee_id group by im.employee_id, im.last_name, im.first_name
关键调整说明
- 分组(GROUP BY):按员工的唯一标识(
employee_id)及姓名字段分组,确保每个员工的结果仅显示一行。 - 聚合函数(MAX):通过
max()取该员工对应课程的最高值——只要该员工完成过对应课程(存在至少一条匹配记录),就返回1,否则返回0。 - 列名修正:为每个课程列设置唯一且清晰的名称,避免原查询中列名重复的问题。
如果你的course_table结构是单条记录包含多门课程字段(如course1、course2),则可以简化为以下查询(无需分组,直接关联后去重即可,但这种表结构设计通常不推荐):
select distinct im.employee_id, im.last_name, im.first_name, case when sc.course1 = 'ABC' then 1 else 0 end as "课程1(ABC)完成情况", case when sc.course2 = 'DEF' then 1 else 0 end as "课程2(DEF)完成情况", case when sc.course3 = 'GHI' then 1 else 0 end as "课程3(GHI)完成情况" from employee_table im join course_table sc on im.employee_id = sc.employee_id
内容的提问来源于stack exchange,提问作者MasonS
相关产品推荐
相关产品推荐

