--示例--示例数据
declare @t table(数值 int,时间 datetime)
insert @t select 100,'2001/10/1'
union all select 105,'2001/10/1'
union all select 100,'2001/10/2'
union all select 105,'2001/10/3'
union all select 105,'2001/10/4'
union all select 105,'2001/10/4'--查询
declare @数值 int,@时间 datetime
select @数值=数值,@时间=时间 from @t
select * from @t where 数值=@数值 and 时间=@时间-1/*--查询结果数值 时间
----------- ---------------------------
105 2001-10-03 00:00:00.000(所影响的行数为 1 行)
--*/
declare @t table(数值 int,时间 datetime)
insert @t select 100,'2001/10/1'
union all select 105,'2001/10/1'
union all select 100,'2001/10/2'
union all select 105,'2001/10/3'
union all select 105,'2001/10/4'
union all select 105,'2001/10/4'--查询
declare @数值 int,@时间 datetime
select @数值=数值,@时间=时间 from @t
select * from @t where 数值=@数值 and 时间=@时间-1/*--查询结果数值 时间
----------- ---------------------------
105 2001-10-03 00:00:00.000(所影响的行数为 1 行)
--*/
不过时间只是用来排序,只确定行的顺序,如:order by 时间
或者
select * from t where 时间 = (select max(时间) from t)来取得最后行的数据.
因为时间是不定的,所以不能用{时间=某个具体数值}来作为抽出条件.这样的话,能写SQL文了吗?
不过,整个处理是放在存储过程中实现,所以,如果确实需要主键定位的话,可以自己定义一个零时表,放一个自增长字段,用它来作为主键定位.(数据比较多,现在测试的就有60多万条).如下:
编号 数值 时间
-------------------
1 100 2001/10/1 ----------------1
2 105 2001/10/1 ----------------2
3 100 2001/10/2 ----------------3
4 105 2001/10/3 ----------------4
5 105 2001/10/4 ----------------5
6 105 2001/10/4 ----------------6
-------------------但是有了主键,下一步又应该怎么处理呢?
现在先抛开效率,只要能做出来就可以.SQL以后再优化,或者进行数据库变更.
create table tb(编号 int identity,数值 int,时间 datetime)
insert tb select 100,'2001/10/1'
union all select 105,'2001/10/1'
union all select 100,'2001/10/2'
union all select 105,'2001/10/3'
union all select 105,'2001/10/4'
union all select 105,'2001/10/4'
go--查询
select * from tb
where 编号>(
select max(编号) from tb
where 数值<>(select top 1 数值 from tb order by 时间 desc))
go--删除测试
drop table tb /*--测试结果编号 数值 时间
----------- ----------- ---------------------------
4 105 2001-10-03 00:00:00.000
5 105 2001-10-04 00:00:00.000
6 105 2001-10-04 00:00:00.000(所影响的行数为 3 行)--*/