我在计算列Cost %
Cost % = Amount/SUM(Amount) * 100
SUM(Amount)等于我提供的数据的2599.30。
SELECT
S.Product_Name,
SPD.UnitPrice,
SPD.Quantity,
SUM(SPD.Quantity * SPD.UnitPrice) AS Amount,
SPD.Quantity * SPD.UnitPrice) / SUM(SPD.Quantity * SPD.UnitPrice) * 100 as [Cost %]
FROM
dbo.Stock_Purchase SP
INNER JOIN dbo.Stock_Purchase_Details SPD ON
SP.Purchase_ID = SPD.Purchase_ID
INNER JOIN dbo.Store S ON SPD.Pro_ID = S.Pro_ID
GROUP BY
S.Product_Name,
SPD.UnitPrice,
SPD.Quantity
我从此查询中获得的输出:
Product_Name UnitPrice Quantity Amount Cost %
pro1 141.55 3 424.65 100.0000000000000
pro2 151.05 3 453.15 100.0000000000000
pro3 40.38 4 161.52 100.0000000000000
pro4 24.08 6 144.48 100.0000000000000
pro5 707.75 2 1415.50 100.0000000000000
我正在寻找的输出:
Product_Name UnitPrice Quantity Amount Cost %
pro1 141.55 3 424.65 16.33
pro2 151.05 3 453.15 17.43
pro3 40.38 4 161.52 6.21
pro4 24.08 6 144.48 5.55
pro5 707.75 2 1415.50 54.45
答案 0 :(得分:2)
首先,您应该开始使用表别名来使您的代码更具可读性。无论如何,你应该尝试:
SELECT S.Product_Name,
SPD.UnitPrice,
SPD.Quantity,
SPD.Quantity * SPD.UnitPrice Amount,
(SPD.Quantity * SPD.UnitPrice)/(SUM(SPD.Quantity * SPD.UnitPrice) OVER()) * 100 [Cost %]
FROM dbo.Stock_Purchase SP
INNER JOIN dbo.Stock_Purchase_Details SPD
ON SP.Purchase_ID = SPD.Purchase_ID
INNER JOIN dbo.Store S
ON SPD.Pro_ID = S.Pro_ID;