我应该在我的其他帖子中提出多个问题。感谢所有帮助过的人,我现在被困在另一个人身上......
使用w3schools db,List SupplierID,SupplierName和ItemSupplied(供应商提供的商品数量),首先按提供的商品数量(降序),然后按供应商名称(升序)对列表进行排序< / p>
SELECT supplierid,
suppliername,
p.productname,
Count(s.supplierid) AS itemssupplied
FROM [Suppliers] AS s
INNER JOIN [Products] AS p
ON p.supplierid = s.supplierid
GROUP BY p.productid,
p.productname
ORDER BY Count (p.productid, p.productname) DESC
order BY s.suppliername
它给了我一个错误,然后我再次订购多个。我认为这里有一点我不太了解。
我的另一个问题是
列出每个类别的客户以及该客户在给定类别中下达的订单总数。在查询中显示三个列:CategoryName,CustomerName和TotalOrders(这是给定类别中给定客户的订单的价格*数量)。 TotalOrders按降序对此数据进行排序。
SELECT cg.CategoryName,
c.CustomerName,
Sum(p.Price * od.Quantity) AS TotalOrders
FROM [products] AS p
INNER JOIN [orderdetails] AS od
ON od.ProductID = p.ProductID
INNER JOIN [orders] AS o
ON o.OrderID = od.OrderID
INNER JOIN [customers] AS c
ON c.customerID = o.CustomerID
INNER JOIN [categories] AS cg
ON cg.CategoryID = p.CategoryID
GROUP BY c.CustomerName
ORDER BY TotalOrders DESC
有人可以检查一下我的查询是否正确吗?再次感谢你!
答案 0 :(得分:1)
问题1
您真的很接近,但您只需要说明ORDER BY
一次(同时确保在GROUP BY
中包含所有显示的字段,除非您要汇总它们):
SELECT SupplierID, SupplierName, p.ProductName, count(s.SupplierID) AS ItemsSupplied
FROM [Suppliers] AS s
INNER JOIN [Products] AS p ON p.SupplierID = s.SupplierID
GROUP BY p.ProductID, p.ProductName, SupplierID, SupplierName -- Added SupplierID, SupplierName
ORDER BY COUNT (p.productID, p.ProductName) DESC, s.SupplierName
请注意,您只需将多个排序放在同一行,并用逗号分隔它们。
问题2
您几乎就在那里,但您需要按任何未聚合的字段进行分组。因此,为了避免出现解析错误,我将cg.CategoryName
添加到GROUP BY
行。
SELECT cg.CategoryName, c.CustomerName, Sum(p.Price*od.Quantity) AS TotalOrders
FROM [Products] AS p
INNER JOIN [OrderDetails] AS od ON od.ProductID = p.ProductID
INNER JOIN [Orders] AS o ON o.OrderID = od.OrderID
INNER JOIN [Customers] AS c ON c.customerID = o.CustomerID
INNER JOIN [Categories] AS cg ON cg.CategoryID = p.CategoryID
GROUP BY c.CustomerName, cg.CategoryName --Added CategoryName
ORDER BY TotalOrders DESC
答案 1 :(得分:0)
第一个有两个order by子句
ORDER BY COUNT (p.productID, p.ProductName) DESC
和
ORDER BY s.SupplierName
当使用group by的查询按列排序时,某些数据库会抱怨所选列
答案 2 :(得分:0)
第一个查询有几个问题:
ProductID
和ProductName
进行分组即使您想要供应商提供的项目数,这意味着您希望按{{1}进行分组}和SupplierID
。SupplierName
函数提供了太多参数,该参数只需一个列名或COUNT
。*
列,但未提及该列。ProductName
提供的产品数量和ORDER BY
。记住这些要点:
SupplierName
您的第二个查询非常接近,您只缺少一点,即您正在寻找该客户在指定类别 中的订单总数>。这意味着除了按SELECT
s.SupplierID,
s.SupplierName,
COUNT(p.ProductID) AS ItemsSupplied
FROM
[Suppliers] AS s
INNER JOIN [Products] AS p ON p.SupplierID = s.SupplierID
GROUP BY
s.SupplierID, s.SupplierName
ORDER BY
ItemsSupplied DESC,
s.SupplierName ASC
进行分组外,您还需要按c.CustomerName
进行分组:
cg.CategoryID