分割范围的日期和时间成为单独的记录

时间:2017-04-03 06:43:38

标签: sql sql-server sql-server-2014

今天我有一些问题,将两个日期与他们的时间分开,他们的范围变成了单独的记录

为了做到这一点,例如我有这个样本

javax.security.auth.callback.CallbackHandler

然后使用脚本或程序,我希望得到这个结果,如下所示

----------------------------------------------------------------
| Record id | date_from               | date_to                |
----------------------------------------------------------------
|     A     | 2017-02-03 08:00:00.000 | 2017-02-04 17:00:00.000|
----------------------------------------------------------------

如何通过这种方式完成这项工作?而且它很有活力。非常感谢你:)

2 个答案:

答案 0 :(得分:1)

可以通过构建计数日期表然后加入表data

来完成
;WITH data AS
(
    SELECT * FROM (VALUES
        ('A', '2017-02-03 08:00', '2017-02-04 17:00'),
        ('B', '2017-02-05 08:00', '2017-02-09 17:00')
    ) t(RecordId, date_from, date_to)
)
,tally AS
(
    -- It just build on the fly, 
    -- actually you can prebuild the table somewhere with DateValue as a key
    SELECT MIN(CAST(date_from AS date)) AS DateValue, MAX(CAST(date_to AS date)) MaxDate FROM data
    UNION ALL SELECT DATEADD(DAY, 1, DateValue), MaxDate FROM tally WHERE DateValue < MaxDate
)
SELECT 
    RecordId, 
    CASE 
        WHEN CAST(date_from AS date) = DateValue THEN date_from 
        ELSE CAST(DateValue AS datetime) 
    END AS date_from,
    CASE 
        WHEN CAST(date_to AS date) = DateValue THEN date_to 
        ELSE DATEADD(SECOND, -1, DATEADD(DAY, 1, CAST(DateValue AS datetime))) 
    END AS date_to
FROM 
    -- The joining condition creates the product effect for date range into separate dates
    data INNER JOIN tally ON DateValue BETWEEN data.date_from AND data.date_to

https://data.stackexchange.com/stackoverflow/query/652790

答案 1 :(得分:0)

您也可以尝试:

DECLARE @StartDate DATETIME='2017-02-04 17:00:00.000',
        @EndDate DATETIME = '2017-02-05 17:00:00.000'
SELECT DateAdd(DAY, nbr - 1, @StartDate) AS date_from,
       DateAdd(DAY, nbr - 1, GetDate()) AS date_to
FROM
  (SELECT ROW_NUMBER() OVER (
                             ORDER BY c.object_id) AS Nbr
   FROM sys.columns c ) nbrs
WHERE nbr - 1 <= DATEDIFF(DAY, @StartDate, @EndDate)