1

我有一个简单的数据集,如下表 1 所示。我想使用表 1 中的列生成两个新列 (START_SHIFT_DT_TIMEEND_SHIFT_DT_TIME)。所需的输出如表 2 所示。

要求是:

  1. 如果START_SHIFT时间从 22:00:00 或之后开始,则实际开始日期为前一天。
  2. 如果START_SHIFT营业时间在 22:00:00 之前开始,则实际开始日期为次日。

我正在使用 SQL 服务器。

表 1

START_SHIFT END_SHIFT       DATE    
22:00:00    06:00:00        1/13/2012 12:00:00 AM
07:00:00    15:00:00        1/13/2012 12:00:00 AM
23:30:00    07:30:00        2/27/2012 12:00:00 AM
00:00:00    08:00:00        2/17/2012 12:00:00 AM
17:00:00    01:00:00        1/1/2012 12:00:00 AM

表 2

START_SHIFT END_SHIFT     DATE                  START_SHIFT_DT_TIME     END_SHIFT_DT_TIME
22:00:00    06:00:00      1/13/2012 12:00:00 AM  1/12/2012 10:00:00 PM  1/13/2012 6:00:00 AM
07:00:00    15:00:00      1/13/2012 12:00:00 AM  1/13/2012 7:00:00 AM   1/13/2012 3:00:00 PM
23:30:00    07:30:00      2/27/2012 12:00:00 AM  2/26/2012 11:30:00 PM  2/27/2012 7:30:00 AM
00:00:00    08:00:00      2/17/2012 12:00:00 AM  2/17/2012 12:00:00 AM  2/17/2012 8:00:00 AM
17:00:00    01:00:00      1/1/2012 12:00:00 AM   1/1/2012 5:00:00 PM    1/2/2012 1:00:00 AM
4

1 回答 1

0
SELECT
  START_SHIFT,
  END_SHIFT,
  DATE,
  DATEADD(SS,
          DATEDIFF(SS,0,START_SHIFT),
          DATEADD(D,
                  CASE WHEN START_SHIFT >= '22:00' THEN -1 ELSE 0 END,
                  DATE)) START_SHIFT_DT_TIME,
  DATEADD(SS,
          DATEDIFF(SS,0,END_SHIFT),
          DATE) END_SHIFT_DT_TIME
FROM TBL

The pattern used in the last column is that the time component in END_SHIFT is converted to seconds and then added to the DATE. In the 4th column, the same pattern is used and it goes through an additional step of adding -1 day (previous) when START_SHIFT is 22:00 or later.

于 2012-09-21T18:48:53.420 回答