我试图通过employees
表加入attendance_chart
表来获取所有员工缺席和现在的总数,其中attendance_status
表包含SELECT
e.id AS employee_id,
COUNT(present_days_chart.id) as present_days_count,
COUNT(absent_days_chart.id) as absent_days_count
FROM
employees e
LEFT JOIN attendance_chart present_days_chart ON e.id = present_days_chart.attendance_for_employee_id AND present_days_chart.attendance_status = 'present'
LEFT JOIN attendance_chart absent_days_chart ON e.id = absent_days_chart.attendance_for_employee_id AND absent_days_chart.attendance_status = 'absent'
WHERE
e.id IN (106,138)
GROUP BY
e.id
中的状态记录}列
class Admin extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->view('dashboard');
}
public function Post()
{
$this->load->view('add_post');
}
}
但是,查询会在每行的present_days_count和absent_days_count列中返回相同数量的记录。
我做错了什么?
答案 0 :(得分:5)
尝试使用CASE WHEN
和SUM
:
SELECT e.id,
SUM(CASE WHEN days_chart.attendance_status = 'present' THEN 1 ELSE 0 END) AS present_days_count ,
SUM(CASE WHEN days_chart.attendance_status = 'absent' THEN 1 ELSE 0 END) AS absent_days_count
FROM employees e
LEFT JOIN attendance_chart days_chart ON e.id = days_chart.attendance_for_employee_id
WHERE e.id in (106,138)
GROUP BY e.id
使用此SUM
+ CASE WHEN
结构,它应计算具有特定attendance_status
的每条记录,并在SUM
和{GROUP BY
的帮助下总结所有计数{1}}
答案 1 :(得分:0)
您是否尝试过稍微改写它?
SELECT
e.id AS employee_id,
COUNT(present_days_chart.id) as present_days_count,
COUNT(absent_days_chart.id) as absent_days_count
FROM
employees e
LEFT JOIN (SELECT * FROM attendance_chart WHERE attendance_status = 'present') AS present_days_chart ON e.id = present_days_chart.attendance_for_employee_id
LEFT JOIN (SELECT * FROM attendance_chart WHERE attendance_status = 'absent') AS absent_days_chart ON e.id = absent_days_chart.attendance_for_employee_id
WHERE
e.id IN (106,138)
GROUP BY
e.id