mysql - 选择列中具有最大值的行
问题描述
我正在尝试选择 numTimesPurchasedTable 中在 numTimesPurchased 列上具有最大值的行
SELECT item, title, MAX(numTimesPurchased)
FROM (SELECT Purchase.item, Item.title, SUM(quantity) AS numTimesPurchased
FROM Item INNER JOIN Purchase ON Item.id = Purchase.item
GROUP BY item, title) AS numTimesPurchasedTable;
numTimesPurchasedTable 看起来像这样
item title numTimesPurchased
1 a 4
2 b 7
3 c 7
但是,我收到错误:“错误代码:1140。在没有 GROUP BY 的聚合查询中,SELECT 列表的表达式 #1 包含非聚合列 'numTimesPurchasedTable.item'”
有没有办法在一个查询中完成此操作?
解决方案
如果您只需要具有最大值的单行,则使用 LIMIT:
SELECT Purchase.item, Item.title, SUM(quantity) AS numTimesPurchased
FROM Item INNER JOIN Purchase ON Item.id = Purchase.item
GROUP BY item, title
ORDER BY numTimesPurchased DESC LIMIT 1;
推荐阅读
- c# - 如何为文档创建第三个签名
- variables - 如何将存储变量的值传递给jmeter中的另一个请求
- java - 两个线程是否有可能面对单个对象实例的死锁?
- machine-learning - 具有单个时间信号输入的 LSTM 多步预测
- ajax - 通过 AJAX 在 Yii2 中验证 Select2
- android-gradle-plugin - 由于“无法从...加载 Maven 元数据”,Gradle 同步失败,但我可以通过浏览器下载文件
- azure - 从 REST API 复制数据非常慢 - ADF
- rest - URL 矩阵参数与路径参数
- mysql - 如何从一个mysql表迁移到另一个包含自动增量列的类似表
- angular - 从 dist 目录中删除未使用的 flag-icon-css 图像