你好!
我的SQL任务有些麻烦,也许有人可以帮我解决这个问题。
我们有2个表:订单和供应商。需要准备一份包含供应商名称,发货项目和总订单百分比的表格。
我几乎完成了整个任务,但是过滤了3个供应商中有2个订单数量高于平均值的问题。
以下是任务说明:选择出货量高于平均水平的出货单 (到“发件人”栏),他们发货的订单数量(到“商品”栏目 发送“)和从总金额(到列 “配额”,值必须为'%'符号)
所以这是我的问题:
SELECT Shippers.ShipperName AS 'Sender', COUNT(*) AS 'Item_Sent',
COUNT(*)/(SELECT COUNT(*) FROM Orders) * 100 AS "Quota"
FROM Orders
JOIN Shippers ON Shippers.ShipperID=Orders.ShipperID
GROUP BY ShipperName
HAVING Item_Sent > (SELECT AVG(Item_Sent) from Orders);
HAVING出现问题... - 订单金额高于平均值时,它不会选择3个供应商中的2个。
答案 0 :(得分:2)
您不应该为列别名使用引号,但最终应该使用引用:
SELECT Shippers.ShipperName AS `Sender`, COUNT(*) AS `Item_Sent`,
COUNT(*)/(SELECT COUNT(*) FROM Orders) * 100 AS "Quota"
FROM Orders
JOIN Shippers ON Shippers.ShipperID=Orders.ShipperID
GROUP BY ShipperName
HAVING Item_Sent > (SELECT AVG(Item_Sent) from Orders);
您也可以尝试不使用别名
SELECT Shippers.ShipperName, COUNT(*),
COUNT(*)/(SELECT COUNT(*) FROM Orders) * 100
FROM Orders
JOIN Shippers ON Shippers.ShipperID=Orders.ShipperID
GROUP BY ShipperName
HAVING COUNT(*) > (SELECT AVG(Item_Sent) from Orders);