所以我在这个表中列出了行:
IDCODE DATETIME DIFFERENCE (MINS)
1 02/03/2011 08:00-----10
2 02/03/2011 08:10-----13
3 02/03/2011 08:23 ----- 2
4 02/03/2011 08:25 ----- 60
5 02/03/2011 09:25 ----- 44
6 02/03/2011 10:20 ----- 14
7 02/03/2011 10:34
我想计算(下一行 - 当前行的时间差)。因此,在第1行中,第2行的日期减去第1行的日期是10分钟的差异,因此它将在第1行中显示为10分钟的差异。
任何帮助将不胜感激
答案 0 :(得分:1)
将表连接到自身,并在连接的On部分,您可以指定类似“ON MyTable.ID = MyTable.ID -1”的内容。
这取决于ID是连续的,没有间隙。
答案 1 :(得分:1)
我使用旧版本的自联接来解决您的问题:
declare @t table (IDCODE int , dt datetime)
insert into @t
values
(1 ,'02/03/2011 08:00')-----10
,(2 ,'02/03/2011 08:10')-----13
,(3 ,'02/03/2011 08:23') ----- 2
,(4 ,'02/03/2011 08:25') ----- 60
,(5 ,'02/03/2011 09:25') ----- 44
,(6 ,'02/03/2011 10:20') ----- 14
,(7 ,'02/03/2011 10:34')
;with cte as
(
select *,rn=ROW_NUMBER() over (order by IDCODE)
from @t
)
select base.IDCODE
, base.dt
, case when future.IDCODE is null
then null
else datediff(minute,base.dt,future.dt)
end as DIFFERENCE
from cte as base
left join cte as future on base.rn+1 = future.rn
结果:
IDCODE dt DIFFERENCE
1 2011-02-03 08:00:00.000 10
2 2011-02-03 08:10:00.000 13
3 2011-02-03 08:23:00.000 2
4 2011-02-03 08:25:00.000 60
5 2011-02-03 09:25:00.000 55
6 2011-02-03 10:20:00.000 14
7 2011-02-03 10:34:00.000 NULL
答案 2 :(得分:1)
使用row_number 1>在Lead
和CTE
上进行演示
此解决方案不依赖于IDCODE作为标识符,而是依赖于 序列,如果IDCODE与
无关Lead and Row_number order by mydatetime
declare @mytable table (idcode int, mydatetime datetime)
insert into @mytable
values
(1 ,'02/03/2011 08:00'),-----10
(2 ,'02/03/2011 08:10'),-----13
(3 ,'02/03/2011 08:23'), ----- 2
(4 ,'02/03/2011 08:25'), ----- 60
(5 ,'02/03/2011 09:25'), ----- 44
(6 ,'02/03/2011 10:20'), ----- 14
(7 ,'02/03/2011 10:34')
-- using Lead
select
mydatetime,
lead(mydatetime,1,null) over (order by idcode) [mynextdatetime],
datediff(minute,mydatetime,lead(mydatetime,1,null) over (order by idcode)) [DatediffMinute]
from @mytable
-- using CTE
;with myDateList as (
select row_number() over (order by idcode) rn,
idcode,
mydatetime
from @mytable
) ,
myNextDate as
(
select
row_number() over (order by idcode) nextrn,
idcode,
mydatetime [nextdate]
from
myDateList
where rn > 1
)
select d.idcode,d.mydatetime, n.nextdate,
datediff(minute,d.mydatetime,n.nextdate) datediffbyminutes
from myDateList D
left outer join myNextDate N
on d.rn = n.nextrn
;
答案 3 :(得分:1)
使用CTE
WITH DateCte AS
(
SELECT
idcode,
mydatetime,
RANK() OVER ( ORDER BY idcode) AS CurrentRank,
(RANK() OVER ( ORDER BY idcode) + 1 )AS NextRank
FROM Table1
)
SELECT
ce.idcode,
DATEDIFF (minute, ce.mydatetime, ne.mydatetime) AS DateDifference
FROM DateCte AS ce LEFT OUTER JOIN DateCte ne ON ce.NextRank = ne.CurrentRank