mysql - MySQL Workbench中两行之间的差异,但未授权LAG
问题描述
我有一个数据集,如本例所示:
id | product_id | date | weight
1 | 454 |2019-06-26 16:08:45| 900
2 | 454 |2019-06-27 13:24:16| 900
3 | 454 |2019-06-28 10:53:42| 899
4 | 352 |2018-04-18 10:53:42| 124
5 | 352 |2018-04-19 15:26:51| 124
6 | 112 |2019-12-08 11:44:01| 065
7 | 375 |2020-03-15 08:23:43| 483
8 | 375 |2020-03-15 18:07:33| 496
9 | 375 |2020-03-16 14:32:24| 496
而且我只想获得与前一个不同或与下一个不同的行。在示例的情况下,预期的输出是:
id | product_id | date | weight
2 | 454 |2019-06-27 13:24:16| 900
3 | 454 |2019-06-28 10:53:42| 899
7 | 375 |2020-03-15 08:23:43| 483
8 | 375 |2020-03-15 18:07:33| 496
但是,我对这个数据库只有读取权限,所以这个LAG()
功能不起作用。我还有什么其他选择?
谢谢!
解决方案
一种方法使用相关子查询:
select t.*
from (select t.*,
(select t2.weight
from t t2
where t2.product_id = t.product_id and t2.date < t.date
order by t2.date desc
limit 1
) as prev_weight,
(select t2.weight
from t t2
where t2.product_id = t.product_id and t2.date > t.date
order by t2.date asc
limit 1
) as next_weight
from t
) t
where prev_weight <> weight or next_weight <> weight;
推荐阅读
- neo4j - 如何将 neo4j 从 2.2.9 升级到 3.4.0?
- python - Keras model.predict 函数给出输入形状错误
- android - 为什么我无法在 Android 中的两个 Fragment 之间切换
- c# - 在导航页面之间移动时应用程序冻结
- output - rstan 如何为单独的链存储后验样本?
- matlab - 多变量梯度下降Matlab - 这两个代码有什么区别?
- python-3.x - ValueError:要解包的值太多(预期为 4),但有四个
- vue.js - 如何从 JS 控制台访问 Vue 组件中的变量?
- ms-access - 为什么错误消息框出现没有错误?
- c - C中的strcmp()函数