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

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

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

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() 函数不起作用。我还有别的选择吗?
谢谢您!

4si2a6ki

4si2a6ki1#

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

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;
dphi5xsq

dphi5xsq2#

您可以尝试:

SELECT DISTINCT *
FROM table t1
WHERE EXISTS (
              SELECT *
              FROM table t2
              WHERE t1.weight <> t2.weight
              AND   t1.product_id = t2.product_id
             )

相关问题