【问题标题】:Compare with Dates and ID?与日期和 ID 进行比较?
【发布时间】:2009-10-06 13:47:21
【问题描述】:

使用 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

等等……,

如何为这种情况编写查询?

【问题讨论】:

    标签: sql sql-server tsql sql-server-2000


    【解决方案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
    */
    

    【讨论】:

    • 对我来说太快了;打算发布同样的东西:)
    猜你喜欢
    • 1970-01-01
    • 2017-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-03
    相关资源
    最近更新 更多