I'm currently trying to implement a bit of code that will take the dates for a given list of 160ish rows and update them to be one minute after another date from the same table.
so for example from these would go from:
> 1058841 2018-06-20 14:15:04.000 Copy of NtO produced
> 1058841 2018-06-14 19:58:03.000 NTO service date set to 24/05/2018
> 969565 2018-06-20 14:15:01.000 17530 Copy of NtO produced
> 969565 2018-06-14 19:58:03.000 148 NTO service date set to 24/05/2018
to this:
> 1058841 2018-06-14 19:59:03.000 Copy of NtO produced
> 1058841 2018-06-14 19:58:03.000 NTO service date set to 24/05/2018
> 969565 2018-06-14 19:59:03.000 17530 Copy of NtO produced
> 969565 2018-06-14 19:58:03.000 148 NTO service date set to 24/05/2018
my code currently is as follows:
declare @thisdate table
(
thisdate datetime,
thisref nvarchar(50)
)
declare @thisdate2 table
(
thisdate2 datetime
)
insert into @thisdate(thisdate) (select te_date from (
select row_number() over (partition by te_system_ref order by (select 0)) as rownumber, te_date from ticket_events where te_system_ref in
(select sl_system_ref from statutory_letter where sl_letter_batch = 9429)and te_event = 'Copy of NtO produced' and te_system_ref = 969565
) t where rownumber = 1)
;
insert into @thisdate(thisref) select te_system_ref from (
select row_number() over (partition by te_system_ref order by (select 0)) as rownumber, te_system_ref from ticket_events where te_system_ref in
(select sl_system_ref from statutory_letter where sl_letter_batch = 9429)and te_event = 'Copy of NtO produced' and te_system_ref = 969565
) t where rownumber = 1
;
insert into @thisdate2(thisdate2) select te_date from (
select row_number() over (partition by te_system_ref order by (select 0)) as rownumber, te_date from ticket_events where te_system_ref in
(select sl_system_ref from statutory_letter where sl_letter_batch = 9429)and te_event like 'NTO service date set to%' and te_system_ref = 969565
) t where rownumber = 1
;
update ticket_events
set te_date = dateadd(minute,1,(select thisdate2 from @thisdate2))
where te_date in (select thisdate from @thisdate) and te_system_ref in (select thisref from @thisdate) and te_event = 'Copy of NtO produced'
However the problem with this is if the select query used to populate the variables produces more than one result, it no longer works. How would I resolve this?
And a quick bonus question, how do I take the last row instead of the first using row numbers?
Any help at all will be greatly appreciated!