日期:2014-05-17  浏览次数:20508 次

sql 分组 嵌套
ID 设备ID 状态 变更日期
1 A1 使用 2012-2-12
2 A1 维修 2012-8-12
3 A1 备用 2012-9-12
4 A1 使用 2012-10-12
5 A1 报废 2012-12-12
6 A2 使用 2012-5-12
7 A2 备用 2012-10-12
8 A2 使用 2012-11-12

求A1,A2的使用时间
A1=8个月  (2012-8-12 - 2012-2-12)+ (2012-12-12 - 2012-10-12) = 8个月
A2=6个月零5天 (2012-10-12 - 2012-5-12) + (dateTime.new - 2012-11-12) = 6个月零5天  

sql 怎么写啊 ~~~  求解

------解决方案--------------------
create table tb(ID int,设备ID varchar(10),状态 nvarchar(10),变更日期 datetime)
insert into tb select 1,'A1','使用','2012-2-12'
insert into tb select 2,'A1','维修','2012-8-12'
insert into tb select 3,'A1','备用','2012-9-12'
insert into tb select 4,'A1','使用','2012-10-12'
insert into tb select 5,'A1','报废','2012-12-12'
insert into tb select 6,'A2','使用','2012-5-12'
insert into tb select 7,'A2','备用','2012-10-12'
insert into tb select 8,'A2','使用','2012-11-12'
go
;with c1 as(
select id+1 id,设备id,'' 状态,convert(varchar(10),getdate(),120)as 变更日期
from tb a
where 状态='使用' and not exists(select 1 from tb where 设备ID=a.设备ID and 变更日期>a.变更日期 and 状态<>'使用')
union all
select * from tb
)
select a.设备ID,sum(datediff(d,a.变更日期,b.变更日期)) as 使用天数
from tb a inner join c1 b on a.设备ID=b.设备ID and a.id=b.id-1
where a.状态='使用'
group by a.设备ID
/*
设备ID       使用天数
---------- -----------
A1         243
A2         188

(2 行受影响)

*/
go
drop table tb
只能以天计,不可以以月计,因为隔月使用,不能确定一个月有几天.