Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Seconds()
Message
From
10/02/2019 13:50:20
Cetin Basoz
Engineerica Inc.
Izmir, Turkey
 
 
General information
Forum:
Visual FoxPro
Category:
Databases,Tables, Views, Indexing and SQL syntax
Title:
Environment versions
Visual FoxPro:
VFP 9
OS:
Windows 10
Network:
Windows 2008 Server
Database:
MS SQL Server
Application:
Desktop
Miscellaneous
Thread ID:
01666213
Message ID:
01666218
Views:
92
Likes (1)
>Sir, I am using SQL SERVER 2008.
>
>Suppose I have following data
>
>
>CREATE CURSOR junk(date t,nSeconds n(4))
>INSERT INTO junk values({^2019-02-08 01:25:28 AM},	0)
>INSERT INTO junk values({^2019-02-08 01:25:29 AM},	0)
>INSERT INTO junk values({^2019-02-08 01:25:55 AM},	0)
>INSERT INTO junk values({^2019-02-09 02:28:29 AM},	0)
>INSERT INTO junk values({^2019-02-09 02:50:18 AM},	0)
>INSERT INTO junk values({^2019-02-09 08:59:17 PM},	0)
>INSERT INTO junk values({^2019-02-09 10:25:39 PM},	0)
>INSERT INTO junk values({^2019-02-12 03:05:19 AM},	0)
>
>
>
>I want to fill nSeconds column like this
>For second record
>
>
>AA={^2019-02-08 01:25:29 AM}-{^2019-02-08 01:25:28 AM}   && 1 Second
>
>
>Second() difference with Previous record.
>
>I need result shown in attached file
>
>I want to update JUNK table in sqlserver.
>
>Thanks in advance

(I don't like "junk" as a tableName at all so I will use "sample" instead):
declare @minDate Datetime
select @minDate = min([date]) from sample;

with tmp (date, nSeconds) as
(
 select [date], 
  case 
    when [date] = @minDate then 0
    else datediff(second, LAG([date], 1,0) over (order by [date]), [date]) 
  end
  from sample
)
update sample
   set nSeconds = tmp.nSeconds 
from tmp 
where sample.[date] = tmp.[date];
Here is a demo:

https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=f07c7e74757ae7ee877eba0fbdf553e5

PS: I later noticed it was MS SQL 2008:
with tmp ([date], rcNo) as 
(
  select [date], row_number() over (order by [date])
  from sample
),
secs ([date], [seconds]) as
(
  select t1.[date], datediff(second,t2.[date], t1.[date])
  from tmp t1 
  left join tmp t2 on t1.rcNo = t2.rcNo+1
)
update sample
   set nSeconds = secs.[seconds]
   from secs 
   where secs.[date] = sample.[date];
Sample:
https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=d2438204892dc3ba11a7ec5121015a68
Çetin Basöz

The way to Go
Flutter - For mobile, web and desktop.
World's most advanced open source relational database.
.Net for foxheads - Blog (main)
FoxSharp - Blog (mirror)
Welcome to FoxyClasses

LinqPad - C#,VB,F#,SQL,eSQL ... scratchpad
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform