使用基于 Avg 的 Max 和 Min 来确定最低平均成本和最高平均成本时出错(MySQL)
Posted
技术标签:
【中文标题】使用基于 Avg 的 Max 和 Min 来确定最低平均成本和最高平均成本时出错(MySQL)【英文标题】:Error using Max and Min based on Avg to determine lowest average cost and highest average cost (MySQL) 【发布时间】:2019-05-07 03:31:03 【问题描述】:我已根据以下确定平均科目费用:
FROM BOOK
JOIN
(SELECT BOOK_SUBJECT,
Avg(BOOK_COST) AS AVGCOST
FROM BOOK
GROUP BY BOOK_SUBJECT) AS SUB USING (BOOK_SUBJECT)
ORDER BY BOOK_TITLE;
但是,我现在需要显示一个学科内最低的平均书籍成本和一个学科内最高的平均书籍成本。我知道我需要使用 MIN 和 MAX,但由于我必须基于 AVG,所以不确定语法。
这是我的尝试......
SELECT BOOK_SUBJECT
FROM BOOK
WHERE BOOK_COST =
(SELECT MIN(AVGCOST)
FROM BOOK)
ORDER BY BOOK_SUBJECT;
SELECT BOOK_SUBJECT
FROM BOOK
WHERE BOOK_COST =
(SELECT MAX(AVGCOST)
FROM BOOK)
ORDER BY BOOK_SUBJECT;
这会产生一个 SQL 错误:字段列表中的未知列“AVGCOST”。我该如何解决这个问题?我知道它正在寻找一个属性并且找不到它,那么需要在代码中添加什么以便 mysql 计算平均值的最小值和最大值?非常感谢回复的人,您的反馈非常好。
【问题讨论】:
你能澄清一下吗?如果同一主题中有 3 本书,它们的价格分别为 5 英镑、10 英镑和 15 英镑,则平均价格为 10 英镑……没有 MIN(AVERAGE) 和 MAX(AVERAGE);也许您可以包括一个简单的 BOOK 表示例和一个您尝试输出的示例? 【参考方案1】:我认为你想要实现的是
SELECT *
FROM BOOK
JOIN
(
SELECT BOOK_SUBJECT,
AVG(BOOK_COST) AS AVGCOST,
MIN(BOOK_COST) AS MINCOST,
MAX(BOOK_COST) AS MAXCOST
FROM BOOK
GROUP BY BOOK_SUBJECT
) AS SUB USING (BOOK_SUBJECT)
ORDER BY BOOK_TITLE;
基于
BOOK_SUBJECT BOOK_TITLE BOOK_COST
------------ ---------- ---------------------
MATHS Book 1 15.99
MATHS Book 2 14.99
MATHS Book 3 13.99
ENGLISH Book A 10.99
ENGLISH Book B 9.99
返回
BOOK_SUBJECT BOOK_TITLE BOOK_COST AVGCOST MINCOST MAXCOST
------------ ---------- --------- ------- ------- -------
MATHS Book 1 15.99 14.99 13.99 15.99
MATHS Book 2 14.99 14.99 13.99 15.99
MATHS Book 3 13.99 14.99 13.99 15.99
ENGLISH Book A 10.99 10.49 9.99 10.99
ENGLISH Book B 9.99 10.49 9.99 10.99
仅提取 MIN/MAX 平均成本(四舍五入到小数点后 2 位)
SELECT
ROUND(MIN(MM.AVGCOST), 2) AS MINAVG,
ROUND(MAX(MM.AVGCOST), 2) AS MAXAVG
FROM
(
SELECT BOOK_SUBJECT,
AVG(BOOK_COST) AS AVGCOST
FROM BOOK
GROUP BY BOOK_SUBJECT
) MM
会回来
MINAVG MAXAVG
------ ------
10.49 14.99
【讨论】:
谢谢@Sean。这是整个代码:SELECT
BOOK_SUBJECT,
Round(AVGCOST, 2) AS "Average Subject Cost"
FROM BOOK
JOIN
(SELECT BOOK_SUBJECT,
Avg(BOOK_COST) AS AVGCOST
Avg(BOOK_COST) AS AVGCOST
FROM BOOK
GROUP BY BOOK_SUBJECT) AS SUB USING (BOOK_SUBJECT)
ORDER BY BOOK_TITLE;
以上是关于使用基于 Avg 的 Max 和 Min 来确定最低平均成本和最高平均成本时出错(MySQL)的主要内容,如果未能解决你的问题,请参考以下文章