简体   繁体   中英

Insert a row without altering table

TL;DR: Is there a way of inserting a row to an intermediate "view" or "table" resulting from a subquery?

Background:

I am not allowed to alter table in database (SQL Server 2014).

The table only records the start time of the task but for another query, I need to find out both the start time and end time of all tasks. I can take the liberty of tasks having no breaks in between them.

Problem

I am able to get the start time and end time for all tasks EXCEPT for the last task by using a JOIN on a.row = b.row - 1.

I need to retrieve all tasks' start and end times, possibly by inserting a row in an intermediate query result "table" or "view" where the timestamp would be NOW().

Tables

INPUT TABLE

TaskID    StartTime
-----------------------------
1         2018-08-10 03:00:00
2         2018-08-10 06:12:00
3         2018-08-11 07:13:00

EXPECTED OUTPUT TABLE

TaskID    StartTime              EndTime
----------------------------------------------------------
1         2018-08-10 03:00:00    2018-08-10 06:12:00
2         2018-08-10 06:12:00    2018-08-11 07:13:00
3         2018-08-11 07:13:00    2018-08-16 15:26:00 (now)

OUTPUT TABLE

TaskID    StartTime              EndTime
----------------------------------------------------
1         2018-08-10 03:00:00    2018-08-10 06:12:00
2         2018-08-10 06:12:00    2018-08-11 07:13:00

CURRENT NON-WORKING CODE

WITH EnterTaskTimes AS ( 
    SELECT ROW_NUMBER()  OVER (ORDER BY StartTime ASC) TaskID
    , [Timestamp] AS StartTime 
    FROM TaskLog
), 
TaskTimes As (
    SELECT
    a.TaskID Task,
    a.StartTime StartTime,
    b.StartTime EndTime
    FROM TaskLog a JOIN TaskLog b
    ON a.TaskID = b.TaskID - 1
)

Thank you,

Use the Lead() function:

-- setup
Create Table Time_Lapse
(
    TaskID Int
    , StartTime DateTime
)

Insert Into dbo.Time_Lapse
(
    TaskID
    , StartTime
)
Select 1, '2018-08-10 03:00:00'
Union All Select 2, '2018-08-10 06:12:00'
Union All Select 3, '2018-08-11 07:13:00'


-- query
Select 
    tl.TaskID
    , tl.StartTime
    , Lead(tl.StartTime, 1, GetDate()) Over (Order By tl.StartTime) As EndTime
From dbo.Time_Lapse As tl

Without having tried, I think something like this should work to 'extend' your original table by one row

...
   Union
Select max(Taskid) as taskid , now() as StartTime
 From TaskLog

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM