sql—mysql workbench中两行之间的差异,但lag未被授权

wvmv3b1j  于 2021-07-29  发布在  Java
关注(0)|答案(2)|浏览(523)

我有一个数据集,如本例所示:

  1. id | product_id | date | weight
  2. 1 | 454 |2019-06-26 16:08:45| 900
  3. 2 | 454 |2019-06-27 13:24:16| 900
  4. 3 | 454 |2019-06-28 10:53:42| 899
  5. 4 | 352 |2018-04-18 10:53:42| 124
  6. 5 | 352 |2018-04-19 15:26:51| 124
  7. 6 | 112 |2019-12-08 11:44:01| 065
  8. 7 | 375 |2020-03-15 08:23:43| 483
  9. 8 | 375 |2020-03-15 18:07:33| 496
  10. 9 | 375 |2020-03-16 14:32:24| 496

我只想得到权重与前一行不同或与下一行不同的行。在本示例中,预期输出为:

  1. id | product_id | date | weight
  2. 2 | 454 |2019-06-27 13:24:16| 900
  3. 3 | 454 |2019-06-28 10:53:42| 899
  4. 7 | 375 |2020-03-15 08:23:43| 483
  5. 8 | 375 |2020-03-15 18:07:33| 496

但是,我对此数据库只有读取权限,因此 LAG() 函数不起作用。我还有别的选择吗?
谢谢您!

4si2a6ki

4si2a6ki1#

一种方法使用相关子查询:

  1. select t.*
  2. from (select t.*,
  3. (select t2.weight
  4. from t t2
  5. where t2.product_id = t.product_id and t2.date < t.date
  6. order by t2.date desc
  7. limit 1
  8. ) as prev_weight,
  9. (select t2.weight
  10. from t t2
  11. where t2.product_id = t.product_id and t2.date > t.date
  12. order by t2.date asc
  13. limit 1
  14. ) as next_weight
  15. from t
  16. ) t
  17. where prev_weight <> weight or next_weight <> weight;
展开查看全部
dphi5xsq

dphi5xsq2#

您可以尝试:

  1. SELECT DISTINCT *
  2. FROM table t1
  3. WHERE EXISTS (
  4. SELECT *
  5. FROM table t2
  6. WHERE t1.weight <> t2.weight
  7. AND t1.product_id = t2.product_id
  8. )

相关问题