我有三个表,我试图从两个表中获取信息,然后对第三个表执行计算并在一个查询中显示所有结果。
(简化的)表格是:
表:employee_work
employee_id name
1 Joe
2 Bob
3 Jane
4 Michelle
表:结转
employee_id days
1 5
2 10
3 3
表:请假
employee_id time_off_type days
1 Carryover 2
1 Leave 3
1 Carryover 1
2 Sick 4
2 Carryover 4
3 Leave 1
4 Sickness 4
我想要的结果是:
employee_id, carryover.days, timeoff.days
1 5 3
2 10 4
3 3 0
但是,当我运行查询时,虽然我在第 1 列和第 2 列中获得了正确的值,但我在第三列中为所有条目重复了相同的数字。
这是我的查询:
Select
employee_work.employee_id,
carryover.carryover,
(SELECT SUM(days) FROM timeoff WHERE timeoff.time_off_type = 'Carryover'
AND timeoff.start_date>='2013-01-01') AS taken
From
carryover Left Join
employee_work On employee_work.employee_id = carryover.employee_id Left Join
timeoff On employee_work.employee_id = timeoff.employee_id Left Join
Where
carryover.carryover > 0
Group By
employee_work.employee_id
我曾尝试在子查询中进行分组,但随后我被告知“子查询返回多行” - 我如何确保子查询尊重联接,因此它一次只查看每个员工,所以我得到我的想要的结果?