使用日期和ID进行比较?(Compare with Dates and ID?)

2019-10-17 19:08发布

使用SQL Server 2000

我想根据Table1.personid得到Table2.TimeIn Table2.TimeOut并且如果Table1.Date = Table3.Date那么就应该采取Table3.TimeIn,Table3.TimeOut。

3个表

表格1

ID    Date  

001 20090503 
001 20090504 
001 20090506 
002 20090505 
002 20090506 

等等...,

表2

ID    TimeIn TimeOut

001 08:00:00 18:00:00
002 08:00:00 21:00:00

等等...,

表3

ID    Date  TimeIn TimeOut

001 20090504 10:00:00 22:00:00
001 20090505 17:00:00 23:00:00
002 20090505 12:00:00 21:00:00 

等等...,

Select Table1.ID, 
       Table1.Date, 
       Table2.TimeIn, 
       Table2.TimeOut 
  from Table1 
Inner Join Table2 on Table1.ID = Table2.ID 

如果Table1.Date = Table3.Date那么就应该采取Table3.TimeIn,Table3.TimeOut其他Table2.TimeIn,Table2.Timeout

预计输出

ID Date TimeIn TimeOut

001 20090503 08:00:00 18:00:00
001 20090504 10:00:00 22:00:00 
001 20090506 08:00:00 18:00:00
002 20090505 12:00:00 21:00:00
002 20090506 08:00:00 21:00:00

等等...,

如何写这个条件查询?

Answer 1:

员工时间表后备?:

SELECT Table1.ID
    ,Table1.Date
    ,COALESCE(Table3.TimeIn, Table2.TimeIn) AS TimeIn
    ,COALESCE(Table3.TimeOut, Table2.TimeOut) AS TimeOut
FROM Table1
INNER JOIN Table2 -- Always have an expected schedule for an employee
    ON Table1.ID = Table2.ID
LEFT JOIN Table3 -- May.may not have an actual schedule for an employee
    ON Table3.ID = Table1.ID
    AND Table3.Date = Table1.Date
/*
ORDER BY Table1.ID
    ,Table1.Date
*/


文章来源: Compare with Dates and ID?