mysql - 计算值之间的列中的减法
问题描述
我有一个带有数值列的表。我想测量最新价格与前一个价格相差 8 点的次数,例如...
First I subtract 1 from 2 166-158=8 I want this to count
Then I subtract 2 from 3 158-143=15 I dont want this to count
Then I subtract 3 from 4 143-140=3 Neither this
Then I subtract 4 from 5 140-132=8 I want his to count
所以sql代码必须返回2个计数
解决方案
使用lag()
:
select count(*)
from (select t.*, lag(price) over (order by id) as prev_price
from t
) t
where price = prev_price - 8;
推荐阅读
- ios - Swift - 如何在不迭代领域对象集合的情况下批量更新对象
- ios - 项目选择需要在vue js多选中点击IOS两次
- android - 如何在 RecyclerView 中获取适配器位置
- amazon-web-services - AWS JS SDK V3(Lambda 模块)- 无法连接到实例元数据服务
- python-3.x - python中多个页面的数据连接出错
- ruby-on-rails - 如何处理在 Rails 命名空间中找不到的路由?
- kotlin - 无法覆盖应用功能
- javascript - 我想用 Meteor 中当前网页的 pdf 发送电子邮件
- mocha.js - 在 Mocha 中,为什么我要使用 only()/skip()?
- c++ - 将文字字符串作为 const char * 参数传递会导致代码分析器错误