[英]MySQL “Inner Join” query from three tables giving wrong result
我正在做一個 HR 項目,我需要從 mysql 數據庫中調用 3 個表值,並且需要基於以下一些標准的自定義 output:但我無法獲得 Z78E6221F6393D.456681htDB3698 我是 mysql 的新手,需要您的指導來獲得 output,如下所示。 提前感謝您的明智建議...
表員工
EMP_ID - EMP_NAME
EID001 - 湯姆
EID002 - 拉里
餐桌考勤
EMP_ID - EMP_NAME - ATTENDANCE_DATE
EID001 - 湯姆 - 20200101
EID002 - 拉里 - 20200101
EID001 - 湯姆 - 20200102
EID002 - 湯姆 - 20200103
EID002 - 湯姆 - 20200104
表 Leave_Record
EMP_ID - EMP_NAME - LEAVE_DATE(FROM) - LEAVE_DATE(TO) - DAYS - LEAVE_TYPE
EID002 - 拉里 - 20200102 - 20200102 - 1 - 休閑
EID002 - 拉里 - 20200103 - 20200103 - 1 - 生病了
EID002 - 拉里 - 20200104 - 20200104 - 1 - 年度
看着 output
EMP_ID - EMP_NAME - WORKING_DAYS - CASUAL_LEAVE - SICK_LEAVE - ANNUAL_LEAVE
EID001 -湯姆 - 4 - 0 - 0 - 0
EID002 - 拉里 - 4 - 1 - 1 - 1
我的 MySql 查詢: SELECT EMP_ID, EMP_Name, SUM(Attendance. ATTENDANCE_DATE,='') as WORKING_DAYS. SUM(Leave_Record,LEAVE_TYPE='CASUAL') as CASUAL. SUM(Leave_Record,LEAVE_TYPE=SICK) as SICK. SUM(Leave_Record,LEAVE_TYPE=ANNUAL) as ANNUAL from Employee, Attendance. Leave_Record where Attendance. EMP_ID = Employee. EMP_ID AND Employee. EMP_ID = Leave_Record. EMP_ID GROUP BY Employee. EMP_ID order by Employee. EMP_ID
SELECT EMP_ID, EMP_Name, SUM(Attendance. ATTENDANCE_DATE,='') as WORKING_DAYS. SUM(Leave_Record,LEAVE_TYPE='CASUAL') as CASUAL. SUM(Leave_Record,LEAVE_TYPE=SICK) as SICK. SUM(Leave_Record,LEAVE_TYPE=ANNUAL) as ANNUAL from Employee, Attendance. Leave_Record where Attendance. EMP_ID = Employee. EMP_ID AND Employee. EMP_ID = Leave_Record. EMP_ID GROUP BY Employee. EMP_ID order by Employee. EMP_ID
您在兩個表中都有多個匹配的行,因此外部聚合會產生錯誤的計數。 您通常會先聚合子查詢,然后加入外部查詢:
select
e.emp_id,
e.name,
coalesce(a.working_days, 0) working_days,
coalesce(cl.casual_leave, 0) casual_leave,
coalesce(cl.sick_leave, 0) sick_leave
from employee e
left join (
select emp_id, count(*) working_days from attendance group by emp_id
) a on a.emp_id = e.emp_id
left join (
select
emp_id,
sum(case when leave_type = 'casual' then days end) casual_leave,
sum(case when leave_type = 'sick' then days end) sick_leave
from leave_record
group by emp_id
) cl on cl.emp_id = e.emp_id
如果leave_record(days)
始終為1
,則第二個子查詢可以簡化為:
left join (
select
emp_id,
sum(leave_type = 'casual') casual_leave,
sum(leave_type = 'sick') sick_leave
from leave_record
group by emp_id
) cl on cl.emp_id = e.emp_id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.