Question

I have question about use NOT EXISTS function in SQL

I have 2 tables. In one I keep records from workers and in other I keep records of workers who have worked for some day. Need help: how to select all workers who have not worked for specific date range and group them by every day in that range. I can get all workers who have worked in that date range, but not those who have not work in same date range

  1. Table1

    • UserID (int)
  2. Table2

    • UserID (int)
    • DayOfWork (datetime)

Example how I select those who have worked:

SELECT     tableWorkingDay.DayOfWork , tableUsers.UserId
FROM       tableWorkingDay INNER JOIN
           tableUsers
           ON tableWorkingDay.UserId= tableUsers.UserId
WHERE     (tableWorkingDay.DayOfWork BETWEEN '1/1/2014' AND '1/31/2014') 
GROUP BY tableWorkingDay.DayOfWork, tableUsers.UserId
ORDER BY tableWorkingDay.DayOfWork 
Was it helpful?

Solution

You want all workers that didnt' work on even a single day in the date range. Let me also assume that you have all the dates somewhere in the table tableWorkingDay.

You need to start with the days. Here is a query to get that:

select distinct wd.DayOfWork
from tableWorkingDay wd
where wd.DayOfWork between '2014-01-01' and '2014-01-31'

Next, you want to cross this with all employees to get a virtual table of all employees and days. Then use left join against the original table and select the places where the left join has no matches:

select days.DayOfWork, users.UserId
from (select distinct wd.DayOfWork
      from tableWorkingDay wd
      where wd.DayOfWork between '2014-01-01' and '2014-01-31'
     ) days cross join
     (select distinct tu.UserId
      from tableUsers tu
     ) users left outer join
     tableWorkingDay wd
     on wd.DayOfWork = days.DayOfWork and wd.UserId = users.UserId
where wd.UserId is null
order by 1, 2;

OTHER TIPS

it's something like this

SELECT     tableWorkingDay.DayOfWork , tableUsers.UserId 
FROM         tableWorkingDay 
INNER JOIN tableUsers ON tableWorkingDay.UserId= tableUsers.UserId 
WHERE    tableWorkingDay.UserId NOT IN (SELECT twd.UserId FROM tableWorkingDay twd WHERE         
twd.DayOfWork BETWEEN '1/1/2014' AND '1/31/2014') 
 GROUP BY tableWorkingDay.DayOfWork, tableUsers.UserId 
ORDER BY tableWorkingDay.DayOfWork 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top