我和老师给出了一些练习题。
到目前为止:
select Sup.supplierID, SupplierName, sum(OD.Quantity)
as ItemSupplied from Suppliers as Sup
inner join Products as P on Sup.SupplierID=P.SupplierID
inner join OrderDetails as OD on
P.ProductID=OD.ProductID
group by Sup.supplierID order by ItemSupplied DESC, SupplierName ASC;
我老师的回答是什么样的(带有SupplierID的回答):
我的问题是我没有和老师一样的答案。 哪一部分我错了?
我通过将sum()更改为COUNT(DISTINCT [OrderDetails的ProductID])得到了它 和ORDER BY此COUNT(DISTINCT [来自OrderDetails的ProductID])首先在DESC中,然后在ASC中的SupplierName:
select Sup.supplierID, SupplierName, count(DISTINCT OD.ProductID)
as ItemSupplied from Suppliers as Sup
inner join Products as P on Sup.SupplierID=P.SupplierID
inner join OrderDetails as OD on
P.ProductID=OD.ProductID
group by Sup.supplierID order by ItemSupplied DESC, SupplierName ASC;
答案 0 :(得分:2)
我怀疑您的老师正在寻找所提供产品的“计数”,如目录中的项目数量。不是订购商品的总数量。规范不是很清楚。
SELECT s.supplierid
, s.suppliername
, COUNT(p.productid) AS cnt_items
FROM Products p
JOIN Suppliers s
ON s.supplierid = p.supplierid
GROUP
BY s.supplierid
, s.suppliername
ORDER
BY COUNT(p.productid) DESC
, s.suppliername ASC
如果我们想要订购已经订购的商品数量,那么供应商的产品数量至少会出现在一个订单上......
SELECT s.supplierid
, s.suppliername
, COUNT(DISTINCT o.productid) AS cnt_items
FROM Products p
JOIN Suppliers s
ON s.supplierid = p.supplierid
JOIN OrderDetails o
ON o.productid = p.productid
GROUP
BY s.supplierid
, s.suppliername
ORDER
BY COUNT(DISTINCT o.productid) DESC
, s.suppliername ASC
答案 1 :(得分:0)
您在组中缺少SupplierName。查询应该失败。