mysql - 使用 Group By 和 Order by Date 选择
问题描述
我的桌子orders
:
ID (int pkey) | store_id (int fkey) | order_category (int fkey) | order_price (deci 10,2) | date (date)
1 | 123 | 5 | 10.25 | 2-11-2021
2 | 678 | 2 | 10.25 | 2-10-2021
3 | 123 | 5 | 10.25 | 2-08-2021
4 | 123 | 3 | 10.25 | 2-04-2021
5 | 678 | 2 | 10.25 | 2-01-2021
6 | 123 | 1 | 10.25 | 2-01-2021
...
我正在尝试获取order_price
每个order_category
.
SELECT order_price FROM orders
WHERE store_id = 123
GROUP BY order_category
ORDER BY date
但它似乎在应用ORDER BY date
时不起作用GROUP BY
。我想要的结果是:
1 | 123 | 5 | 10.25 | 2-11-2021
4 | 123 | 3 | 10.25 | 2-04-2021
6 | 123 | 1 | 10.25 | 2-01-2021
使用 MySQL8.0.23
解决方案
您可以尝试使用按类别分组的最大日期的子查询
select o.order_price, t.order_category
from orders
INNER JOIN (
SELECT order_category, max(date) max_date
order_price
FROM orders
WHERE store_id = 123
GROUP BY order_category
) t on t.order_category = o.order_category
AND t.max_date = o.date
ORDER BY date
推荐阅读
- azure-functions - Azure函数知道域
- javascript - 通过 JS 函数添加行,并在选择选项中添加一个单元格
- c# - Ajax 请求不会在 Safari 和 Ipad 上调用控制器,在 Iphone 上可以
- ifc - 在不运行 BIMServer 的情况下运行 BIMSurfer 需要帮助
- git - 如何在 Git 中添加隐藏文件
- matlab - 当集群在每个时间步发生变化时,如何获取网络中节点所属的集群的列表/向量?
- javascript - 在移动设备上隐藏元素
- sql - ASP.Net 网站上的数据安全
- automationanywhere - 将文件从一个文件夹复制到另一个文件夹
- swift - 使用 Just 加载数据时 iOS 应用程序崩溃