Попробуйте это:
Declare @tab table(media bigint,[Time] datetime)
insert into @tab
SELECT 10010101,'2019-01-01 19:38' Union All
SELECT 10010101,'2019-01-01 21:38' Union All
SELECT 25757858,'2019-01-02 08:30' Union All
SELECT 25757858,'2019-01-02 12:00'
;with cte
As
(
Select media,[Time] as [1.Time],Lead([Time]) over(Partition by media order by [Time] desc) as [2.Time]
from @tab
)
Select *,
CONVERT(varchar, DATEDIFF(n, [2.Time],[1.Time])/60) + ':'
+ RIGHT('0' + CONVERT(varchar, (DATEDIFF(n, [2.Time],[1.Time])%60)), 2) As [Minus Time]
from cte where [2.Time] is not NULL
Если для каждого носителя есть более 2 строк, и если вы хотите получить разницу во времени между первой и последней записью (порядок по времени), попробуйте запрос ниже:
Declare @tab table(media bigint,[Time] datetime)
insert into @tab
SELECT 10010101,'2019-01-01 19:38' Union All
SELECT 10010101,'2019-01-01 20:00' Union All
SELECT 10010101,'2019-01-01 21:38' Union All
SELECT 25757858,'2019-01-02 08:30' Union All
SELECT 25757858,'2019-01-02 12:00'
;with cte1
As
(
Select *,
row_number() over (partition by media order by [Time] asc) as seqnum_asc,
row_number() over (partition by media order by [Time] desc) as seqnum_desc
From @tab
)
,cte
As
(
Select media,Lead([Time]) over(Partition by media order by [Time] desc) as [1.Time],[Time] as [2.Time]
from cte1 where seqnum_asc = 1 or seqnum_desc = 1
)
Select *,
CONVERT(varchar, DATEDIFF(n, [1.Time],[2.Time])/60) + ':'
+ RIGHT('0' + CONVERT(varchar, (DATEDIFF(n, [1.Time],[2.Time])%60)), 2) As [Minus Time]
from cte where [1.Time] is not NULL