MySQL计数可以从2个表开始,但不是重复日期

时间:2015-10-17 20:46:34

标签: mysql duplicates

我在mysql中有2个表 1张公共假日表:

id   empid      date
1      10     2015-10-17
2      10     2015-12-24
3      10     2016-01-01
4      11     2015-10-17
5      11     2015-12-24
6      11     2016-01-01

我有第二张假期在

id    employeeid           date
1      10               2015-10-15
2      10               2015-10-16
3      10               2015-10-17
4      10               2015-10-18
5      11               2015-11-11

问题是如何将两个表一起加入并计算任何重复日期(两个表中的日期)计数应该是6天假期,因为2015-10-17在两个表中都是员工ID 10.表中有多个员工ID和日期。

employee 10 count 6
employee 11 count 4

我尝试过内连接但无法解决问题

1 个答案:

答案 0 :(得分:1)

select count(t.u_date) as employee_count, t.employee_id
from (
    select date as u_date, employee_id
    from table

    union

    select date as u_date, employee_id
    from table
) as t
group by t.employee_id

FIDDLE_EXAMPLE

编辑:

您可以执行此更新的查询

SELECT 
    ...
FROM employees AS e
LEFT JOIN 
(   SELECT empid, date, hours
    FROM holidays_taken
    UNION
    SELECT empid, date, hours
    FROM public_holidays
) AS h ON e.id = h.empid
WHERE e.id = 1
GROUP BY Year