我需要在1996年9月计算出每种产品占总收入的比例。数据在3个表中
表1:订单详细信息
OrderDetailID OrderID ProductID Quantity-
-------------------------------------------
1 10248 11 12
2 10248 42 10
3 10248 72 5
4 10249 14 9
5 10249 51 40
6 10250 41 10
表#2:产品
ProductID ProductName SupplierID CategoryID Unit Price
-----------------------------------------------------------------------------------------------------
1 Chais 1 1 10 boxes x 20 bags 18
2 Chang 1 1 24 - 12 oz bottles 19
3 Aniseed Syrup 1 2 12 - 550 ml bottles 10
4 Chef Anton's Cajun Seasoning 2 2 48 - 6 oz jars 22
5 Chef Anton's Gumbo Mix 2 2 36 boxes 21.35
6 Grandma's Boysenberry Spread 3 2 12 - 8 oz jars 25
7 Uncle Bob's Organic Dried Pears 3 7 12 - 1 lb pkgs. 30
表#3:订单
OrderID CustomerID EmployeeID OrderDate ShipperID
------------------------------------------------------
10248 90 5 1996-07-04 3
10249 81 6 1996-07-05 1
10250 34 4 1996-07-08 2
10251 84 3 1996-07-08 1
10252 76 4 1996-07-09 2
10253 34 3 1996-07-10 2
10254 14 5 1996-07-11 2
我猜这些步骤是:
我已经完成了第一步
SELECT
Orders.OrderID,
Orders.OrderDate,
OrderDetails.Quantity,
OrderDetails.ProductID
FROM
Orders
INNER JOIN
OrderDetails ON Orders.OrderID = OrderDetails.OrderID
WHERE
OrderDate LIKE '1996-09%';
预期结果:
OrderID OrderDate Quantity ProductID
-----------------------------------------
10295 1996-09-02 4 56
10296 1996-09-03 12 11
10296 1996-09-03 30 16
10296 1996-09-03 15 69
10297 1996-09-04 60 39
但是我不知道如何执行步骤2。非常感谢你!
答案 0 :(得分:2)
使用窗口功能:
SELECT od.ProductID,
SUM(od.Quantity),
SUM(od.Quantity) * 1.0 / SUM(SUM(od.Quantity)) OVER () as ratio
FROM Orders o INNER JOIN
OrderDetails od
ON o.OrderID = od.OrderID
WHERE o.OrderDate >= '1996-09-01' AND o.OrderDate < '1996-10-01'
GROUP BY od.ProductID;
答案 1 :(得分:1)
W3Cschool的交互式SQL惯例似乎不支持窗口功能。而且,我没有找到定义变量的方法,因此不得不两次提到相同的常数(年和月)。在现实生活中,我建议使用解析函数,或者至少为多个地方使用的值声明一个变量。
无论如何,看起来像下面的代码可以满足您的需求:
SELECT
od.ProductID,
MIN(o.OrderDate) as SalesStart,
MAX(o.OrderDate) as SalesEnd,
SUM(od.Quantity) as SoldQty,
SUM(od.Quantity * p.Price) as SoldAmt,
SUM(od.Quantity * p.Price) * 1.0 /
(
SELECT SUM(odAll.Quantity * pAll.Price)
FROM OrderDetails odAll
INNER JOIN Orders as oAll
ON oAll.OrderID = odAll.OrderID
INNER JOIN Products as pAll
ON odAll.ProductID = pAll.ProductID
WHERE oAll.OrderDate LIKE '1996-09%') as PortionInTotalSales
FROM Orders as o
INNER JOIN OrderDetails as od
ON o.OrderID = od.OrderID
INNER JOIN Products as p
ON od.ProductID = p.ProductID
WHERE o.OrderDate LIKE '1996-09%'
GROUP BY od.ProductID