需要修改查询而不使用交叉/外部应用

时间:2019-05-24 06:26:58

标签: sql sql-server tsql sql-server-2012

[my_type
  my_string = 'one'
  my_number = 1
]
[my_type
  my_string = 'two'
  my_number = 4
]
[my_type
  my_string = 'alfred'
  my_number = 7
]

除了 UNKNOWN 以外,我需要了解 READY 状态与下一个 READY HAS PAPER 之间的时间间隔状态。 未知我需要跳过。 结果应如下所示:

enter image description here

这是我的查询,但是我不喜欢使用交叉/外部申请。在性能和速度方面,我需要您的建议,以及如何修改此查询。

create table PrinterData(
    Dt DateTime not null,
    Status nvarchar(50) not null    
)

insert into PrinterData
values
('05.24.2019 00:00:00', 'READY'),
('05.24.2019 00:01:00', 'READY'),
('05.24.2019 00:02:00', 'NO PAPER'),
('05.24.2019 00:03:00', 'UNKNOWN'),
('05.24.2019 00:04:00', 'UNKNOWN'),
('05.24.2019 00:05:00', 'READY'),
('05.24.2019 00:06:00', 'READY'),
('05.24.2019 00:07:00', 'READY'),
('05.24.2019 00:08:00', 'NO PAPER'),
('05.24.2019 00:09:00', 'UNKNOWN'),
('05.24.2019 00:10:00', 'HAS PAPER'),
('05.24.2019 00:11:00', 'NO PAPER')

2 个答案:

答案 0 :(得分:2)

使用lead()功能

DEMO

select *,datediff(SECOND,dt,nexttime) as diff from 
(
select *,lead(dt) over(order by dt) as nexttime,lead(status) over(order by dt) as nextstatus
from PrinterData
where Status<>'UNKNOWN'
)A where status='NO PAPER'

输出:

Dt                  Status      nexttime            nextstatus  diff
24/05/2019 00:02:00 NO PAPER    24/05/2019 00:05:00 READY       180
24/05/2019 00:08:00 NO PAPER    24/05/2019 00:10:00 HAS PAPER   120
24/05/2019 00:11:00 NO PAPER        

答案 1 :(得分:1)

您可以通过使用左联接和row_number()来做到这一点

with cte as
(
select a.Dt, a.Status, b.Dt as Dt_Next_Status, b.Status as Next_Status,
DATEDIFF(SECOND, a.Dt, b.Dt) as Diff,
row_number()over(partition by a.DT order by b.Dt) rn
from PrinterData a
left join
(
    select  Dt, Status from PrinterData where Status not in ('UNKNOWN', 'NO PAPER') 
) b on  b.Dt > a.Dt
where a.Status = 'NO PAPER' 
) 
select * from cte where rn=1

demo in fiddle