将单个日期记录与多个时隙结合使用

时间:2014-02-21 09:27:13

标签: sql sql-server sql-server-2008-r2

以下是用于填充事件槽的表格。

活动表

EventID | Name         | EventDateTime(SMALLDATETIME)       
--------+--------------+-----------------------------
   1    | Tech Session | 2014-02-21 00:00:00 
   2    | Job Session  | 2014-02-25 00:00:00 

插槽表

SlotID  | EventId| StartTime(TIME)  |  EndTime(TIME)   |
--------+--------------+---------------------+----------
   1    | 1      | 10:00:00.0000000 | 10:45:00.0000000 |
   2    | 1      | 10:45:00.0000000 | 11:30:00.0000000 |
   3    | 1      | 11:30:00.0000000 | 12:15:00.0000000 |
   4    | 1      | 12:15:00.0000000 | 13:00:00.0000000 |
   5    | 2      | 11:00:00.0000000 | 13:00:00.0000000 |
   6    | 2      | 13:00:00.0000000 | 15:00:00.0000000 |

预期的AvailableSlots:如何查询以获得以下结果?

Name         | StartDateTime       |  EndDateTime        |
--------+--------------+---------------------+------------
Tech Session | 2014-02-21 10:00:00 | 2014-02-21 10:45:00 |
Tech Session | 2014-02-21 10:45:00 | 2014-02-21 11:30:00 |
Tech Session | 2014-02-21 11:30:00 | 2014-02-21 12:15:00 |
Tech Session | 2014-02-21 12:15:00 | 2014-02-21 13:00:00 |
Job Session  | 2014-02-25 11:00:00 | 2014-02-21 13:00:00 |
Job Session  | 2014-02-25 13:00:00 | 2014-02-21 15:00:00 |

2 个答案:

答案 0 :(得分:2)

请尝试:

SELECT 
    Name, 
    DATEADD(SECOND, DATEDIFF(SECOND, 0, StartTime), EventDateTime) StartDateTime, 
    DATEADD(SECOND, DATEDIFF(SECOND, 0, EndTime), EventDateTime) EndDateTime
FROM EventTable a INNER JOIN SlotsTable b ON a.EventId=b.EventId

答案 1 :(得分:2)

您可能还想考虑[StartTime]和[EndTime]之间日间移位的可能性。 这会使我的回答无效

SELECT a.name, 
       a.eventdatetime + b.starttime StartDateTime, 
       a.eventdatetime + b.endtime   Enddatetime 
FROM   event a 
       JOIN slot b 
         ON a.eventid = b.eventid