SQL NOT EXISTS函数

时间:2014-01-20 01:59:20

标签: sql exists

我对SQL中使用NOT EXISTS函数有疑问

我有2张桌子。在一个我记录工人和其他人的记录,我记录有一天工作的工人。需要帮助:如何选择所有未在特定日期范围内工作的工人,并按该范围内的每一天进行分组。我可以得到所有在该日期范围内工作的工人,但不能获得那些在相同日期范围内工作的工人

  1. 表1

    • UserID(int)
  2. 表2

    • UserID(int)
    • DayOfWork(datetime)
  3. 示例我如何选择有效的人:

    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 
    

2 个答案:

答案 0 :(得分:2)

您希望所有工作人员在日期范围内甚至没有工作。我还假设你在表tableWorkingDay中的所有日期都有。{/ p>

你需要从日子开始。这是一个得到它的查询:

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

接下来,您希望与所有员工交叉,以获得所有员工和日期的虚拟表格。然后对原始表使用left join并选择left join没有匹配项的位置:

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;

答案 1 :(得分:0)

就是这样的

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