组合2使用日期选择查询,然后加入2个表

时间:2012-08-28 14:34:52

标签: mysql sql

我试图加入我的查询,但我在周日时间陷入困境,

我有一个非常基本和直接的加入查询,计算员工工作的所有工作时间,正常时间和加班时间,查询工作完美,但是当我想加入星期日时间时,一切都变得混乱......

没有星期天时间的完整查询: -

SELECT
`empl_attendance`.`employee_id`,
`employee`.`employee_surname`,
`employee`.`employee_first_name`,
`employee`.`employee_second_name`,
FORMAT((IF(SUM...some basic maths...)),1) AS nt,
FORMAT((...some basic maths...),1) AS ot,
FORMAT((...some basic maths...),1) AS total
FROM
`empl_attendance`
WHERE
 (`empl_attendance_date` BETWEEN '$start_date' AND '$end_date')
INNER JOIN 
`employee` 
ON `empl_attendance`.`employee_id`=`employee`.`employee_id` 
GROUP BY `employee_id`

但我需要结合以下查询,它基本上计算每个员工的星期日总时数。查询工作正常,我只是在努力将两个查询结合起来:

SELECT SUM(`empl_attendance_total`) AS sundays
FROM `empl_attendance`
WHERE
(`empl_attendance_date` BETWEEN '$start_date' AND '$end_date')
AND
WEEKDAY(`empl_attendance_date`) > 5
GROUP BY `employee_id`

感谢名单

1 个答案:

答案 0 :(得分:0)

您可以使用案例陈述执行此操作:

 SELECT  ea.`employee_id`, e.`employee_surname`,  e.`employee_first_name`,  e.`employee_second_name`,
         FORMAT((IF(SUM...some basic maths...)),1) AS nt,
         FORMAT((...some basic maths...),1) AS ot,
         FORMAT((...some basic maths...),1) AS total,
         sum(case when weekday(ea.empl_attendance_date) > 5 then ea.empl_attendance_total end) as SundayTotal
 FROM empl_attendance ea join
      employee e
      ON ea.`employee_id = e.employee_id
  WHERE  ea.empl_attendance_date BETWEEN '$start_date' AND '$end_date'
  GROUP BY `employee_id`  

我假设以FORMAT开头的行正在寻找非星期日日期,或者至少包括它们,如果这是你想要的。