Pregunta

I have a Table containing historical data. Every day the same staff list will be added with the new dates (between 1200-12500 staff each day however only a few staff might be newly added todaysDate or they may have left the company yesterday and not showing on todays list).

I want to know each day which staff wasn't on yesterday list, it is new staff and the staff was showing yesterday but not today because they left company. I have tried the following but no joy please help my historical table is like below and I need a script to get the rows for ID4 and ID5 only.

StaffID StaffName CensusDate
ID1 Staff1 02/03/2021
ID1 Staff1 03/03/2021
ID2 Staff2 02/03/2021
ID2 Staff2 03/03/2021
ID3 Staff3 02/03/2021
ID3 Staff3 03/03/2021
ID4 Staff4 02/03/2021 not showing today
ID5 Staff5 03/03/2021 is newly added today
ID6 Staff6 02/03/2021
ID6 Staff6 03/03/2021
ID7 Staff7 02/03/2021
ID7 Staff7 03/03/2021
SELECT StaffID, StaffNAME, CensusDate
FROM table1 AS A 
LEFT JOIN table1 AS B 

ON A.StaffID = B.StaffID AND A.date = GETDATE())  AS date) 
and B.date = CAST(DATEADD(day, -1, convert(date, GETDATE())) AS date) 
AND A.staffID IS NULL
¿Fue útil?

Solución

There's likely a simpler way, but I think this achieves what you're looking for:

WITH CTE_TodaysStaff AS
(
    SELECT DISTINCT T1.StaffID
    FROM table1 AS T1
    WHERE T1.CensusDate = CAST(GETDATE() AS DATE)
),
CTE_NotShowingToday AS
(
    SELECT DISTINCT T1.StaffID
    FROM table1 AS T1
    LEFT JOIN CTE_TodaysStaff AS T2
         ON T1.StaffID = T2.StaffID
    WHERE T1.CensusDate = CAST(DATEADD(DAY, -1, GETDATE()) AS DATE)
        AND T2.StaffID IS NULL
 ),
CTE_NewToday AS
(
    SELECT DISTINCT T1.StaffID
    FROM CTE_TodaysStaff AS T1
    LEFT JOIN table1 AS T2
        ON T1.StaffID = T2.StaffID
        AND T2.CensusDate < CAST(GETDATE() AS DATE)
    WHERE T2.StaffID IS NULL
 )

 SELECT T1.StaffID, T1.StaffNAME, T1.CensusDate, 
     CAST(CASE WHEN T2.StaffID IS NULL THEN 0 ELSE 1 END AS BIT) AS IsNotShowingToday,
     CAST(CASE WHEN T3.StaffID IS NULL THEN 0 ELSE 1 END AS BIT) AS IsNewToday
FROM table1 AS T1
LEFT JOIN CTE_NotShowingToday AS T2
    ON T1.StaffID = T2.StaffID
LEFT JOIN CTE_NewToday AS T3
    ON T1.StaffID = T3.StaffID

Otros consejos

Not sure I completely understand your intention or the difference between Table1 and Table2. If you are trying to find just the IDs that only occur once in the last two days.

SELECT StaffID, count(StaffID)
FROM Table1 
WHERE CensusDate >= cast(dateadd(day, -2, getdate()) as date)
Group By StaffID
Licenciado bajo: CC-BY-SA con atribución
No afiliado a dba.stackexchange
scroll top