Compare with Dates and ID?

别来无恙 提交于 2019-12-13 03:50:53

问题


Using SQL Server 2000

I want to get Table2.TimeIn Table2.TimeOut according to Table1.personid and also If Table1.Date = Table3.Date then it should take a Table3.TimeIn, Table3.TimeOut.

3 Tables

Table1

ID    Date  

001 20090503 
001 20090504 
001 20090506 
002 20090505 
002 20090506 

So on…,

Table2

ID    TimeIn TimeOut

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

So on…,

Table3

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 

So on…,

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

If Table1.Date = Table3.Date then it should take Table3.TimeIn, Table3.TimeOut else Table2.TimeIn, Table2.Timeout

Expected Output

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

So on…,

How to write a query for this condition?


回答1:


Employee time schedule fallback?:

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
*/


来源:https://stackoverflow.com/questions/1525705/compare-with-dates-and-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!