mysql - 从同一行中选择具有相关价格列的最新日期时间列
问题描述
我的数据库中有一张表,它正在跟踪一些价格。这些列是:id
, product
, factory
, seller
, platform
,price
和inserted
。
每天每 6 小时都会有新的记录与当前价格一起存储。例子:
1, Product 1, Factory 1, Seller 1, Platform 1, 99.99, 2019-08-07 02:12:35
2, Product 1, Factory 1, Seller 1, Platform 1, 95.99, 2019-08-06 20:12:35
现在我尝试选择带有价格的最新条目。一个条目应该是唯一的product
, factory
, seller
, platform
。所以我的sql查询现在是:
SELECT *
FROM prices
GROUP
BY product
, factory
, seller
, platform
ORDER
BY inserted DESC
, price ASC
但是我现在如何获取每个条目的最新价格?一种解决方案是选择MAX(`inserted`)
,但如何从MAX(`inserted`)
行中获取价格?
解决方案
select p1.* from
prices p1
join
(
SELECT `product`, `factory`, `seller`, `platform`, max(inserted) as max_inserted
FROM `prices`
GROUP BY `product`, `factory`, `seller`, `platform`
) p2 on p1.product = p2.product
and p1.factory = p2.factory
and p1.seller = p2.seller
and p1.platform = p2.platform
and p1.inserted = p2.max_inserted
内部选择获取每个组的最新日期。然后加入反对以仅获取包含价格的相关记录。
推荐阅读
- python - 防止睡眠模式 python (Wakelock on python)
- reactjs - NextJS - 无效的挂钩调用。Hooks 只能在函数组件的主体内部调用
- c# - 如何使用 .net 框架安装创建 c# 应用程序设置文件?
- ios - 创建新分支不会反映 Xcode 项目中的所有目标
- android - Gradle 同步失败:找不到任务“:cdvPrintProps”的参数的leftShift()方法
- firebase - 如何从异步函数中正确获取字符串?
- javascript - 如何使用javascript替换对象中的字符和符号
- android - 如何使用 volley 读取 XML 中的变量
- java - 有多个数据源时的Spring动态事务管理器
- python - python dockerpy 令牌问题使用 jupyter notebook 运行 docker