我正在尝试从具有max(col)的表中选择一行。但是匹配列是错误的。它返回表本身的第一行,而不是max()值的相应列。
select
article, max(totalsale) as maxsale
from
(select
article, sum(sold) as totalsale
from art6maanden
group by article) as maxsale
所以子查询会返回:
productA | 12
....
productZ | 70
完整查询返回:
productA | 70
它应该回归
productZ | 70
因为70是最大值
我正在使用MySQL
答案 0 :(得分:2)
实际上,上面的查询将由MS SQL Server投诉,错误消息说“maxsale.article”列在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。
所以,也许你可以添加一个ORDER BY语句。
SELECT TOP 1 article, totalsale as maxsalevalue
FROM
(SELECT article, sum(sold) as totalsale
FROM art6maanden
GROUP BY article) as maxsale
ORDER BY totalsale DESC
编辑由于不允许使用ORDER BY。我将建议使用HAVING语句的解决方案。
SELECT article, sum(sold) as totalsale
FROM art6maanden
GROUP BY article
HAVING sum(sold) = (
SELECT MAX(totalsales) AS MaxSale
FROM
(SELECT article, sum(sold) as totalsale
FROM art6maanden
GROUP BY article) Ref
)
上述查询按照以下3个步骤完成。
如果我错了,请纠正我。
答案 1 :(得分:-1)
在下面的查询中,您可以在“TotalSalesPerItem”的位置使用您的子查询。
DECLARE @MaxSale int;
Set @MaxSale = (select MAX(TotalSale)from TotalSalesPerItem);
select Item from TotalSalesPerItem
where TotalSale = @MaxSale
它将显示最大销售项目。