我需要一些帮助来解决我的作业中的一个问题,我现在已经尝试了大约一个小时而且无法让它运行。
列出购买的商品数量超过每位顾客的平均商品数量
表格如下:
Customer(Cnum, CustomerName, Address)
Item(Inum, ItemName, Manufacturer, Year)
Bought(Cnum, Inum, Date, Quantity)
Prefer(Inum, Cnum)
我能想到的最好的是,它需要是每个客户的总数量与数量的总体平均值相比较。我尝试过各种形式的查询:
SELECT Cnum
FROM Bought
WHERE
(
SELECT Cnum, SUM(Quantity)
FROM Bought
GROUP BY Cnum;
) >
(
SELECT AVG(Quantity)
FROM Bought
);
但是它返回一个错误 - (phpMyAdmin没有告诉我问题是什么,只是没有执行并且没有连接页面,这意味着我的查询中出错)
我还尝试使用以下命令返回更高的SUM:
SELECT SUM(Quantity)
FROM Bought
WHERE SUM(Quantity) > AVG(Quantity);
同样的问题。
任何帮助都会受到赞赏,甚至可以解释第二个失败的原因。
答案 0 :(得分:4)
您可能需要查看SQL的HAVING子句。
注意:由于这是家庭作业,我故意不给你完整的答案。
答案 1 :(得分:3)
为什么不试试这个。
SELECT `Cnum` , Sum( Quantity )
FROM `bought`
GROUP BY `Cnum`
HAVING Sum( Quantity ) > ( SELECT AVG( Quantity ) FROM Bought )
答案 2 :(得分:1)
尝试这可能有帮助
SELECT Cnum, SUM(Quantity)
FROM Bought
GROUP BY Cnum
HAVING SUM(OrderQuantity) > avg(Quantity)
答案 3 :(得分:1)
尝试以下:
SELECT Cnum
FROM Bought
having SUM(Quantity) > (SELECT avg(Quantity) FROM Bought)
order by SUM(Quantity) desc
答案 4 :(得分:1)
试试这个
SELECT Cnum, Inum, SUM(Quantity) sum, AVG(QUANTITY) average
from bought group by cnum,inum having sum > average