SQL如何求表中相邻的两条记录的某字段的值之差

lt2024 2008-04-10 04:27:55
如何求表中相邻的两条记录的某字段的值之差;;;
如何求表中相邻的两条记录的某字段的值之差;;;
如何求表中相邻的两条记录的某字段的值之差;;;
高手来帮下忙呀
...全文
1703 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
greenhawk 2009-06-27
  • 打赏
  • 举报
回复
求表中相邻的两条记录的某字段的值之差
select a.v1-b.v1
from (select id,v1 from t2 where id>1) a,
(select id,v1 from t2 where id<>(select max(id) from t2)) b
where a.id=b.id+1

问题描述搞清要心静!我初遇到时对这个小问题就蒙 惨啊!
lt2024 2008-04-15
  • 打赏
  • 举报
回复
谢谢各位了,问题解决
-狙击手- 2008-04-10
  • 打赏
  • 举报
回复
declare @t table(ID int,值  int)
insert @t select
1 , 50 union select
2 , 70 union select
3 , 40 union select
4 , 60 union select
5 , 45 union select
6 , 80


select id/2,sum(case when id%2 =1 then 值 else 0 end) - sum(case when id%2 =0 then 值 else 0 end)
from (select id+1 as id ,值 from @t) b
group by id/2

/*

----------- -----------
1 20
2 20
3 35

(所影响的行数为 3 行)
*/
sweetweiwei 2008-04-10
  • 打赏
  • 举报
回复
CREATE TABLE a
(
id int,
price int
)
insert into a values(1 , 50)
insert into a values(2 , 70)
insert into a values(3 , 40)
insert into a values(4 , 60)
insert into a values(5 , 45)
insert into a values(6 , 80)
select c.price - d.price
from
(select * from a where id%2 = 0) c
inner join (select * from a where id%2 = 1) d on d.id+1 = c.id
-----------
20
20
35

(3 row(s) affected)
-狙击手- 2008-04-10
  • 打赏
  • 举报
回复
select id/2,sum(case when id%2 =0 then 值 else 0 end) - sum(case when id%2 =1 then 值 else 0 end) 
from ta
group by id/2
lt2024 2008-04-10
  • 打赏
  • 举报
回复
问题是如何查出相邻的两条呢
比如:
ID 值
1 50
2 70
3 40
4 60
5 45
6 80
我要的结果是
20
20
35
也就是第二条减第一条,第三条减第四条,第六条减第五条
能不能帮写个例子看看,谢谢了!!
lt2024 2008-04-10
  • 打赏
  • 举报
回复
问题是如何查出相邻的两条呢
比如:
ID 值
1 50
2 70
3 40
4 60
5 45
6 80
我要的结果是
20
20
25
也就是第二条减第一条,第三条减第四条,第六条减第五条
能不能帮写个例子看看,谢谢了!!
nzperfect 2008-04-10
  • 打赏
  • 举报
回复
用减法

34,594

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧