SQL Server 查询时间段

本文详细介绍了一种使用SQL进行复杂数据处理的方法,包括创建表格、插入数据、使用子查询和游标等高级技巧来处理多台机器的工作日志数据,并通过一系列的SQL操作实现了对这些数据的有效整合与分析。

create table ABSWorkLog
(
id int identity(1,1),
MachineCode varchar(50),
startTime smalldatetime,
endTime smalldatetime
)
go

insert absworklog values ('abs1','2008-02-02','2008-02-09')
insert absworklog values ('abs1','2008-02-13','2008-02-26')
insert absworklog values ('abs1','2008-03-02','2008-03-26')
insert absworklog values ('abs2','2008-01-26','2008-02-06')
insert absworklog values ('abs2','2008-02-24','2008-03-08')
insert absworklog values ('abs3','2008-02-07','2008-02-25')
go

select * from absworklog

select * into #abs1worklog from absworklog where machinecode='abs1'
select * from #abs1worklog

select * into #otherabsworklog from absworklog where machinecode<>'abs1'
select * from #otherabsworklog

select DISTINCT machinecode into #otherabsname from absworklog where machinecode<>'abs1'
select * from #otherabsname absworklog

create table #temp
(
machinecode varchar(50),
stopTime int
)
go
select * from #temp

declare @startTime smalldatetime,@endTime smalldatetime

DECLARE MyCursor CURSOR FOR
SELECT startTime,endTime FROM #abs1worklog
open MyCursor
FETCH NEXT FROM MyCursor INTO @startTime, @endTime
WHILE @@fetch_status = 0
BEGIN
select a.machinecode,
t=(case when b.startTime is null then convert(int,@endTime)-convert(int,@startTime)
when b.startTime<@startTime and b.endTime<@endTime then convert(int,@endTime)-convert(int,b.endTime)
when b.startTime>@startTime and b.endTime>@endTime then convert(int,b.startTime)-convert(int,@startTime)
when b.startTime>@startTime and b.endTime<@endTime then convert(int,b.startTime)-convert(int,@startTime)+convert(int,@endTime)-convert(int,b.endTime)
end)
into #mid from #otherabsname a
right join #otherabsworklog b on b.machinecode=a.machinecode
where (b.startTime<@startTime and b.endTime>@startTime and b.endTime<@endTime)
or (b.startTime>@startTime and b.endTime<@endTime)
or (b.startTime>@startTime and b.startTime<@endTime and b.endTime>@endTime)
or (b.starttime<@startTime and b.endTime>@endTime)

declare @name varchar(50),@t int
declare MidCurrsor CURSOR FOR
select machinecode,t from #mid
open MidCurrsor

FETCH NEXT FROM MidCurrsor INTO @name, @t
WHILE @@fetch_status = 0
BEGIN

insert #temp values (@name,@t)

FETCH NEXT FROM MidCurrsor INTO @name, @t
end
DEALLOCATE MidCurrsor
drop table #mid

FETCH NEXT FROM MyCursor INTO @startTime, @endTime
END
DEALLOCATE MyCursor
GO

select machinecode,sum(stoptime) from #temp GROUP BY machinecode

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值