在sql查询中计算列问题

时间:2016-02-26 18:27:14

标签: sql sql-server sql-server-2008

我在计算列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

1 个答案:

答案 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;