首页 新闻 会员 周边

请问:SQL根据刚插入的值找到最近插入相同的值

0
悬赏园豆:20 [已解决问题] 解决于 2014-08-28 08:52

id SID Time Dose
1 1 2014-08-13 01:00:00.000 123.45
2 1 2014-08-13 02:00:00.000 145.89
3 2 2014-08-13 02:00:00.000 0.01
4 1 2014-08-13 03:00:00.000 167.09
5 2 2014-08-13 03:00:00.000 1.98
6 3 2014-08-13 03:00:00.000 6.09
7 1 2014-08-13 04:00:00.000 177.26
比如:
我刚插入的是第7条,SID为 1 ,怎么通过刚插入的这条数据的SID找到上一条SID也为1的那条数据,随便求出刚插入的Dose和找到前一条Dose的差值!
加加貝的主页 加加貝 | 菜鸟二级 | 园豆:274
提问于:2014-08-17 00:51
< >
分享
最佳答案
0

写个function,参数为SID,

create function demo

(@SID) returns int

as begin

declare @id1 int

declare @id2 int

set @id1 = SELECT TOP 1 id From tabelName WHERE SID=@SID ORDER BY Time DESC

set @id2 = SELECT TOP 1 id From tabelName WHERE SID=@SID AND id<@id1 ORDER BY Time DESC

RETURN @id1-@id2

end

收获园豆:20
Firen | 大侠五级 |园豆:5385 | 2014-08-17 08:07

放在数据库中执行的时候报错,

消息 102,级别 15,状态 1,过程 demo,第 2 行
')' 附近有语法错误。
消息 156,级别 15,状态 1,过程 demo,第 6 行
关键字 'select' 附近有语法错误。
消息 137,级别 15,状态 2,过程 demo,第 6 行
必须声明标量变量 "@SID"。
消息 156,级别 15,状态 1,过程 demo,第 7 行
关键字 'select' 附近有语法错误。
消息 137,级别 15,状态 2,过程 demo,第 7 行
必须声明标量变量 "@SID"。
消息 178,级别 15,状态 1,过程 demo,第 8 行
在此上下文中不能使用带有返回值的 RETURN 语句。

加加貝 | 园豆:274 (菜鸟二级) | 2014-08-18 09:24

@Summer丿文: 基本思路都有了,你只要稍加修改就行了…

Firen | 园豆:5385 (大侠五级) | 2014-08-18 11:38

@Summer丿文: 

create function func_demo
(@SID int)
returns float
as
begin
declare @dose1 float
declare @dose2 float
declare @id1 int
SELECT top 1 @dose1=dose,@id1=id From tableName WHERE SID=@SID ORDER BY Time DESC
SELECT top 1 @dose2=dose From tableName WHERE SID=@SID AND id<@id1 ORDER BY Time DESC
RETURN @dose1-@dose2
end

select func_demo(1) as SID为1的最后两条记录的Dose之差

会飞的金鱼 | 园豆:881 (小虾三级) | 2014-08-27 19:57
其他回答(5)
0

查最大时间里 sid=1的就行了

望着天的蜗牛 | 园豆:354 (菜鸟二级) | 2014-08-17 21:09
0

select t1.sid, t1.dose, (t1.dose - t2.dose) as delta from t t1 inner join t t2 on t1.sid=t2.sid

where t1.sid=@sid

and t1.id in (select top 1 id from t where sid=t1.sid order by id desc)

and t2.id in (select top1 id from t where sid=t1.sid and id < t1.id order by id desc)

519740105 | 园豆:5810 (大侠五级) | 2014-08-18 09:34
0

Inserted 表用于存储 INSERT 和 UPDATE 语句所影响的行的副本。在一个插入或更新事务处理中,新建行被同时添加到 inserted 表和触发器表中。

你插入的新数据的时候 通过inserted 可以拿到sid

wolfy | 园豆:2636 (老鸟四级) | 2014-08-18 13:15
0

直接取到最后两条数据,然后在程序里面计算一下差值也是可以的呢。

select top 2 * from Table1
where SID=1 order by id desc

Alex_QY1987 | 园豆:1888 (小虾三级) | 2014-08-18 16:45
0
select top 2 * into #t from tablename where SID=1 order by Time desc

select b.id as 刚插入的id,a.id as 前一条的id, (b.Dose-a.Dose) as 刚插入与前一条的Dose之差 from #t as a,#t as b where a.id<b.id
会飞的金鱼 | 园豆:881 (小虾三级) | 2014-08-27 19:43
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册