日期:2014-05-17 浏览次数:20455 次
if(object_id('t1') is not null) drop table t1
go
create table t1
(
[管子类型] varchar(10),
[管子数量] int
)
go
insert into t1
select 'AA',3 union all
select 'A5',5
go
if(object_id('t2')is not null)drop table t2
go
create table t2
(
[管子类型] varchar(10),
[每周差值] int,
[时间] datetime
)
go
insert into t2
select 'AA',1,'2012-11-11' union all
select 'AA',2,'2012-11-18' union all
select 'A5',1,'2012-11-12' union all
select 'A5',3,'2012-11-19'
go
select t1.[管子类型],t1.[管子数量]-t2.[每周差值]as[管子数量],t2.[每周差值]as [最近差值],t2.[时间]
from t1 inner join (select [管子类型], [每周差值],[时间]
from t2 where exists(select 1 from t2 as t
where t2.[管子类型]=[管子类型] and t2.[时间]>[时间])) as t2 on t2.[管子类型]=t1.[管子类型]
/*
管子类型 管子数量 最近差值 时间
---------- ----------- ----------- -----------------------
AA 1 2 2012-11-18 00:00:00.000
A5 2 3 2012-11-19 00:00:00.000
(2 行受影响)
*/
create table t1 (管子类型 varchar(10),管子数量