此刻我在使用SQL时遇到问题。
我使用W3School
的示例数据库这就是我现在拥有的:
SELECT
Categories.CategoryID,
Categories.CategoryName,
COUNT(Products.CategoryID) AS CountProduct
FROM
Categories
INNER JOIN
Products ON Products.CategoryID = Categories.CategoryID
GROUP BY
CategoryName
ORDER BY
CategoryName ASC
输出:
CategoryID CategoryName CountProduct
-----------------------------------------
1 Beverages 12
2 Condiments 12
3 Confections 13
4 Dairy Products 10
5 Grains/Cereals 7
6 Meat/Poultry 6
7 Produce 5
8 Seafood 12
这:
SELECT
Categories.CategoryID,
Categories.CategoryName,
COUNT(OrderDetails.ProductID) AS CountOrder
FROM
Categories
LEFT JOIN
Products ON Products.CategoryID = Categories.CategoryID
LEFT JOIN
OrderDetails ON OrderDetails.ProductID = Products.ProductID
GROUP BY
CategoryName
ORDER BY
CategoryName ASC
输出:
CategoryID CategoryName CountOrder
------------------------------------------------
1 Beverages 93
2 Condiments 49
3 Confections 84
4 Dairy Products 100
5 Grains/Cereals 42
6 Meat/Poultry 50
7 Produce 33
8 Seafood 67
我只想要这个结果:
CategoryID CategoryName CountProduct CountOrder
-------------------------------------------------------
1 Beverages 12 93
2 Condiments 12 49
3 Confections 13 84
4 Dairy Products 10 100
5 Grains/Cereals 7 42
6 Meat/Poultry 6 50
7 Produce 5 33
8 Seafood 12 67
我试图将两个查询合并为一个,但是得到了错误的结果。
谢谢
答案 0 :(得分:0)
使用标量子查询
SELECT Categories.CategoryID, Categories.CategoryName, Count(Products.CategoryID) as CountProduct,
(select Count(OrderDetails.ProductID) from orderdetails where OrderDetails.ProductID = Products.ProductID) as CountOrder
FROM Categories
INNER JOIN Products On Products.CategoryID = Categories.CategoryID
Group By CategoryName
ORDER BY CategoryName ASC
答案 1 :(得分:0)
由于这是一次学习课程,似乎他们正在尝试向您介绍非重复计数,因此请使用以下查询,
SELECT Categories.CategoryID, Categories.CategoryName, COUNT(DISTINCT Products.PRODUCTID) as ProductCout, Count(OrderDetails.ProductID ) as CountOrder
FROM Categories
LEFT JOIN Products On Products.CategoryID = Categories.CategoryID
LEFT JOIN OrderDetails ON OrderDetails.ProductID = Products.ProductID
Group By Categories.CategoryID, Categories.CategoryName