简体   繁体   中英

I have to find the names of the employees who have never worked for two consecutive days in the same center

I have to create a code, in sql, that allows me to find the id of the employees who haven't worked for two days in a row My data has this structure:

id_emp date id_center
0001 2020-12-11 0045
0001 2020-12-12 0045
0001 2020-12-13 0045
0002 2020-12-11 0047
0002 2020-12-13 0047
0003 2020-12-11 0043
0003 2020-12-12 0043
... ... ...

The table to be returned must be structured like this:

id_emp
0002
select distinct id_emp
from mystery_table_name
where id_emp not in (
    select distinct id_emp
    from mystery_table_name a
    join mystery_table_name b on b.id_emp=a.id_emp and b.id_center=a.id_center and b.date=a.date + interval 1 day
)

Though looking for employees in your table of who worked when and where is strange, and will leave out employees who have never worked. Surely you have an employee table.

This should list the distinct id_emps that have at least a single record that are more than 2 days apart:

SELECT
    DISTINCT t1.id_emp
FROM <table_name> AS t1
LEFT JOIN <table_name> AS t2 ON t1.id_emp = t2.id_emp
    -- join the records that are less than 2 days apart
    AND TIMESTAMPDIFF(DAY, t1.date, t2.date) < 2
-- select the records which coudn't be joined, i.e they're more than 2 days apart
WHERE t2.id_emp IS NULL
;

Test this:

WITH cte AS (
    SELECT id_emp, DATEDIFF(date, LAG(date) OVER (PARTITION BY id_emp, id_center ORDER BY date)) = 1 adjacent
    FROM src_table
),
SELECT id_emp
FROM cte
GROUP BY id_emp
HAVING NOT SUM(adjacent)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM