使用OVER()为SQL Server 2012中的每一行计算%

时间:2015-07-14 16:39:37

标签: sql sql-server select sql-server-2012 partitioning

我需要有关如何计算每行两个单元格之间百分比的问题的指导。我在SQL Server 2012上。下面是我当前数据集的结构。

Customer_Number    Price_Last_Year      Price_Today
---------------------------------------------------
909523                   154               190
20175808                 154               100
21808187                 154               190
22792798                 184               284
23256155                 154               230

基本上,我要做的是包含一个额外的列,用于计算每个特定行的(Price_Today)/Price_Last_Year)百分比。我正在使用窗口OVER()函数,但它无法正常工作。

这就是我想要的新数据集的样子:

Customer_Number Price_Last_Year     Price_Today     Percentage_AS ofToday%
909523                   154               190                 23.3%
20175808                 154                  100             -35.1%
21808187                 154               190                 23.3%
22792798                 184               284                 54.3%
23256155                 154               230                 49.3% 

这是我对百分比计算的查询:

SELECT DISTINCT
   Customer_Number,
   Price_Last_Year,
   Price_Today,
   [Percentage AS of Today%]=SUM(Price_Today)100.0/(Price_Last_Year) OVER()
FROM 
   tabl2 a
GROUP BY 
   Customer_Number, Price_Today, Price_Last_Year

我已尝试了OVER()百分比计算的多种变体。我甚至试过像[Percentage AS of Today%]=SUM(Price_Today)100.0/(Price_Last_Year) OVER() (PARTITION BY Customer_Number)这样的东西,它会抛出一个错误。

如何使用OVER()计算每行的百分比?

1 个答案:

答案 0 :(得分:1)

如果您的计算在同一行的两列之间,则不需要over()子句或group by子句 - 只需将两者分开。从1减去并乘以100可以得到一个很好的百分比表示:

SELECT Customer_Number, 
       Price_Last_Year, 
       Price_Today, 
       (1 - (Price_Today/Price_Last_Year)) * 100 AS [Percentage AS of Today%]
FROM   tabl2