0

我有三个表,我试图从两个表中获取信息,然后对第三个表执行计算并在一个查询中显示所有结果。

(简化的)表格是:

表: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

我曾尝试在子查询中进行分组,但随后我被告知“子查询返回多行” - 我如何确保子查询尊重联接,因此它一次只查看每个员工,所以我得到我的想要的结果?

4

1 回答 1

1

您的问题的答案是使用相关子查询。在这种情况下,您不需要timeoff两次提及该表:

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' and
         timeoff.employee_id = employee_work.employee_id
  ) AS taken
From
  carryover Left Join
  employee_work On employee_work.employee_id = carryover.employee_id
Where
  carryover.carryover > 0
Group By
  employee_work.employee_id;

另一种结构是对子from句中的所有员工进行分组。您也可以删除该employee_work表,因为它似乎没有被使用。(您可以使用carryover.employee_idid。)

Select co.employee_id, co.carryover, et.taken
From carryover c Left Join
     (SELECT employee_id, SUM(days) as taken
      FROM timeoff
      WHERE timeoff.time_off_type = 'Carryover' and
            timeoff.start_date>='2013-01-01'
     ) et
     on co.employee_id = et.employee_id
 Where c.carryover > 0;

我认为没有group by必要。如果是,那么您可能应该在原始查询中有一个聚合函数。

于 2013-08-02T17:46:38.213 回答