我正在尝试定义故障单在特定任务中停留的时间。我有专栏。我的SQL如下所示。
select
[number],
datestamp,
assignment_group,
[sequence]
from #ranking1
order by [number],[sequence]
我确信有一种简单的方法可以做到这一点虽然我不太确定它是什么。我的数据目前看起来像:
ticket no Datestamp taskNo ranking
IM123456 3/24/2016 13:44 task1 1
IM123456 3/24/2016 17:01 task2 2
IM123456 4/20/2016 11:57 task3 3
IM123456 5/26/2016 10:50 task3 4
IM123456 7/29/2016 15:39 task1 5
IM123456 8/2/2016 13:15 task2 6
IM123456 10/25/2016 15:42task1 7
IM123456 10/26/2016 16:27task2 8
IM321654 4/5/2016 11:53 task4 1
IM321654 4/8/2016 16:06 task1 2
IM321654 4/11/2016 13:33 task6 3
IM321654 5/12/2016 15:58 task1 4
我希望我的最终结果是
Number Task Number_days
IM123456 task1 4
IM123456 task2 111
IM123456 task3 100
IM123456 task1 3
IM123456 task4 0
IM123456 task6 31
我希望我能够理解。我正在使用SQL studio 2016
答案 0 :(得分:0)
您可以使用LAG
查看以前的记录。因此,当您查看一个[number]
和任务(assignment_group
)并按datestamp
对其记录进行排序时,您需要其他所有记录并从其自己的减去前一个datestamp
。 / p>
select
[number],
assignment_group,
datediff(day, datebefore, datestamp) as number_days
from
(
select
[number],
datestamp,
assignment_group,
row_number() over (partition by [number], assignment_group order by datestamp) as rn,
lag(datestamp) over (partition by [number], assignment_group order by datestamp)
as datebefore
from #ranking1
) data
where rn % 2 = 0
order by [number], datestamp;
或者使用rn % 2 = 1
和LEAD
来获取 next datestamp
。然后你还会显示有开场记录的数字,但还没有关闭的数字。
在此处尝试:http://rextester.com/JAT25484并在此处:http://rextester.com/BEHBO43980。