我已根据以下各项确定了平均科目费用:
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计算平均值和最小值?非常感谢那些回答,您的反馈非常棒。
答案 0 :(得分:0)
我认为您想要实现的目标是
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