私はあなたがこれをどのように作成できるか少しサンプルを作成します。
create table #table (item char, not_active int, active int, created datetime)
insert into #table values('A', 0, 1, '2017-01-01 10:03:15')
insert into #table values('A', 1, 0, '2017-01-01 12:05:55')
insert into #table values('A', 0, 1, '2017-01-01 13:05:55')
insert into #table values('A', 1, 0, '2017-02-03 12:05:55')
insert into #table values('A', 0, 1, '2017-02-05 13:05:55')
insert into #table values('B', 1, 0, '2017-01-10 04:05:20')
insert into #table values('B', 0, 1, '2017-01-10 07:05:20')
declare @very_hard table (item char,
not_active int,
active int,
created datetime,
before datetime,
afters datetime,
days_diff_stoped int,
hourstoped int)
declare very_hard_challenge cursor Local
for
select
item,
active,
not_active,
created,
LAG(created,1,0)over(partition by item order by created) as before,
LEAD(created,1,0)over(partition by item order by created) as afters,
datediff(day,LAG(created,1,0)over(partition by item order by created),created) as days_diff_stoped
from #table
--where item = 'B'
order by created asc
declare @item char,
@not_active int,
@active int,
@created datetime,
@days_diff_stoped int,
@before datetime,
@afters datetime
open very_hard_challenge
fetch next from very_hard_challenge into @item, @not_active, @active, @created, @before, @afters, @days_diff_stoped
WHILE @@FETCH_STATUS=0
begin
declare @datebegin datetime = @before
declare @hourstoped int = 0
if @datebegin != '1900-01-01 00:00:00.000'
begin
while @datebegin < convert(datetime,@created)
begin
if datepart(hour,@datebegin) in(0,1,2,3,4,5)
begin
set @hourstoped = @hourstoped+1
end
set @datebegin = DATEADD(hour,1,@datebegin)
end
end
insert into @very_hard values (@item, @not_active, @active, @created, @before, @afters, @days_diff_stoped, @hourstoped)
fetch next from very_hard_challenge into @item, @not_active, @active, @created, @before, @afters, @days_diff_stoped
end
close very_hard_challenge
deallocate very_hard_challenge
select * from @very_hard
このコードはシンプルですが、改善することができます。誰でもこのコードについて質問すれば教えてください。私は答えを可能にします。
視覚的な結果は、スキーマと併せて役立ち、正しいデータベースにフラグを立てることもできます – maSTAShuFu
どのDBMSを使用していますか? Postgres?オラクル? DB2?ファイアバード? –
T-SQLでは、DATEDIFFを使用して、任意のビジネスロジックに基づいて日付にロジックを送信します。 –