日期数据表查询问题
就一张数据表中,表有三项,分别是日期,状态,持续时间(就是两个状态间的时间差,一般是后一个减去前一个)
最后一个是当前时间减去状态时间的得到的4058
请问下假如给定一个时间段2011-6-9 9:30 ---- 2011-6-9 16:00,如何查询出之间的数据结果(如下面)?
算的结果如下:
2011-6-9 9:30 工作 40
2011-6-9 10:10 坏机 61
2011-6-9 11:11 换型 61
2011-6-9 12:12 计划停机 58
2011-6-9 13:10 损失 60
2011-6-9 14:10 停产 110
2011-6-9 16:00 停产
最后一个停产状态是延续14:00的状态
附原始数据
(发布了图,只能手写了)
2011-6-9 9:10 工作 60
2011-6-9 10:10 坏机 61
2011-6-9 11:11 换型 61
2011-6-9 12:12 计划停机 58
2011-6-9 13:10 损失 60
2011-6-9 14:10 停产 4058
这代码改如何写呢?十万火急,求指教
[解决办法]
create table tb(日期 datetime,状态 nvarchar(10),持续时间 int)insert into tb select '2011-6-9 9:10','工作',60insert into tb select '2011-6-9 10:10','坏机',61insert into tb select '2011-6-9 11:11','换型',61insert into tb select '2011-6-9 12:12','计划停机',58insert into tb select '2011-6-9 13:10','损失',60insert into tb select '2011-6-9 14:10','停产',4058godeclare @dt1 datetime,@dt2 datetimeset @dt1='2011-6-9 9:30'set @dt2='2011-6-9 16:00';with c1 as(select top 1 日期,状态,持续时间-datediff(mi,日期,@dt1)持续时间 from tb where 日期<=@dt1 order by 日期 descunion allselect 日期,状态,持续时间 from tb where 日期>@dt1 and 日期<@dt2),c2 as(select top 1 日期,状态,datediff(mi,日期,@dt2)持续时间 from c1 order by 日期 descunion allselect top 1 @dt2,状态,null from c1 order by 日期 desc)select * from c1 a where not exists(select 1 from c2 where 日期=a.日期)union allselect * from c2 order by 日期/*日期 状态 持续时间----------------------- ---------- -----------2011-06-09 09:10:00.000 工作 402011-06-09 10:10:00.000 坏机 612011-06-09 11:11:00.000 换型 612011-06-09 12:12:00.000 计划停机 582011-06-09 13:10:00.000 损失 602011-06-09 14:10:00.000 停产 1102011-06-09 16:00:00.000 停产 NULL(7 行受影响)*/godrop table tb