SQL:使用另一列计算新列中的百分比

时间:2014-10-30 10:37:06

标签: sql sql-server

我发现很难描述我想在标题中做什么,但我会在这里更具体。 我有一个相当长的查询:

 SELECT 

    /*Amount earned with validation to remove outlying figures*/

    Case When SUM(t2.[ActualSalesValue])>=0.01 OR SUM(t2.[ActualSalesValue])<0 Then SUM(t2.[ActualSalesValue]) ELSE 0 END AS 'Amount', 

    /*Profit earned (is already calculated then input into db, this just pulls that figure*/

    SUM(t2.[Profit]) AS 'Profit', 

    /*Product Type - pulls the product type so that we can sort by product*/

    t1.[ucIIProductType] AS 'Product Type', 

    /*Profit Percentage - This is to calculate the percentage of profit based on the sales price which uses 2 different columns - Case ensures that there are no wild values appearing in the reports as previously experienced*/

    Case When SUM(t2.[ActualSalesValue])>=0.01 OR SUM(t2.[ActualSalesValue])<0 THEN (SUM(t2.[Profit])/SUM(t2.[ActualSalesValue])) ELSE 0 END AS 'Profit Percentage',

/*Percentage of Turnover*/
    *SUM(t2.[ActualSalesValue])/(Select SUM(t2.[ActualSalesValue]) OVER() FROM [_bvSTTransactionsFull]) AS 'PoT'

    /*The join is connect the product type with the profit and the amount*/

    FROM  [dbo].[StkItem] AS t1
    INNER JOIN [dbo].[_bvSTTransactionsFull] AS t2

    /*There attirbutes are the links between the tables*/
    ON t1.[StockLink]=t2.[AccountLink]

    WHERE t2.[TxDate] BETWEEN '1/Aug/2014' AND '31/Aug/2014' AND ISNUMERIC(t2.[Account]) = 1

    Group By t1.[ucIIProductType]

“营业额百分比”部分我遇到了麻烦 - 我试图根据总金额计算金额的百分比 - 使用相同的列。例如:我想获取第1行中的Amount值,然后将其除以整个列的总量,然后将该值列在新列中。但是我一直得到错误或者我继续得到1(因为它想要将值除以相同的值。任何人都可以告诉我正确的语法来解决这个问题:

/*Percentage of Turnover*/
        *SUM(t2.[ActualSalesValue])/(Select SUM(t2.[ActualSalesValue]) OVER() FROM [_bvSTTransactionsFull]) AS 'PoT'

1 个答案:

答案 0 :(得分:0)

我认为您需要以下其中一项:

SUM(t2.[ActualSalesValue])/(Select SUM(t.[ActualSalesValue]) FROM [_bvSTTransactionsFull] t) AS PoT

或:

SUM(t2.[ActualSalesValue])/(SUM(SUM(t2.[ActualSalesValue])) OVER() ) AS PoT

注意:您应该仅对字符串和日期常量使用单引号,而不是对列和表名称使用单引号。如果您需要转义名称,请使用方括号。