MySQL Workbench 中两行之间的差异,但 LAG 未获得授权
Difference between two rows in MySQL Workbench, but LAG is not authorized
我有一个如本例所示的数据集:
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 DISTINCT *
FROM table t1
WHERE EXISTS (
SELECT *
FROM table t2
WHERE t1.weight <> t2.weight
AND t1.product_id = t2.product_id
)
一种方法使用相关子查询:
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;
我有一个如本例所示的数据集:
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 DISTINCT *
FROM table t1
WHERE EXISTS (
SELECT *
FROM table t2
WHERE t1.weight <> t2.weight
AND t1.product_id = t2.product_id
)
一种方法使用相关子查询:
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;