【发布时间】:2020-09-07 00:52:40
【问题描述】:
我的mysql表和价格
+----------+-----+----------+
|product_id|price|date_at |
+----------+-----+----------+
| 1 |41.50|2020-09-01|
| 1 |99.50|2020-09-02|
| 1 |41.50|2020-09-03|
| 1 |41.50|2020-09-04|
| 1 |41.50|2020-09-05|
| 1 |9.90 |2020-09-06|
+----------+-----+----------+
我可以得到今天和昨天的价格:
select today.price,
yesterday.price as yesterday_price
from prices today
left join prices yesterday on today.product_id = yesterday.product_id
where yesterday.date_at = '2020-09-05' <-- I need to have it dynamic
and today.date_at = '2020-09-06'
我需要将昨天的日期作为 N 天期间 MAX(price) 的任何日期。
示例: finally.date_at = 相同 product_id 过去 20 天的最高价格
也许我应该在左连接而不是在哪里使用更多代码。 请告诉我如何更改我的查询。
【问题讨论】:
-
很难说出您的要求。让我猜猜:(i)你给查询一个数字,例如20、(ii)查询返回20天前到今天价格最高的日期。对吗?
-
指定精确的 MySQL 版本。
-
也许您应该提供所需的结果以及具有适当代表性的数据集。见meta.stackoverflow.com/questions/333952/…