SQL:如何使用具有多列的分区来计算百分比增加

问题描述

我有 6 列名为 TOTAL_STOCK_VALUE,VALUE_UNRESTRICTED,fiscal_year,fiscal_period,plant,storage_location。我想创建一个新列,其中包含来自列 TOTAL_STOCK_VALUE,VALUE_UNRESTRICTED 的百分比增加值。

Sample data : 
TOTAL_STOCK_VALUE  VALUE_UNRESTRICTED  fiscal_year  fiscal_period  plant  storage_location
336.0                228.0                 2019         10          ABC         AR40
418.0                209.0                 2019         10          ABC         IN80
162.0                0.000                 2020         04          CTF         KK29
86412.0              53060.0               2020         04          ARZ         HD91
Desired Output :
TOTAL_STOCK_VALUE  VALUE_UNRESTRICTED  fiscal_year  fiscal_period  plant  storage_location  New
336.0                228.0                 2019         10          ABC         AR40       32.14%
418.0                209.0                 2019         10          ABC         IN80        50%
162.0                0.000                 2020         04          CTF         KK29        100%
86412.0              53060.0               2020         04          ARZ         HD91       38.59%  

使用的查询

select
    TOTAL_STOCK_VALUE,storage_location,((TOTAL_STOCK_VALUE - VALUE_UNRESTRICTED) / TOTAL_STOCK_VALUE) * 100 over(partition by fiscal_year,storage_location) as New
from
    MyTable

上述查询未给出所需结果并引发错误。 任何帮助将不胜感激。

解决方法

根据您想要的输出,您似乎只想这样做:

select
    TOTAL_STOCK_VALUE,VALUE_UNRESTRICTED,fiscal_year,fiscal_period,plant,storage_location,(1 - (VALUE_UNRESTRICTED / TOTAL_STOCK_VALUE)) * 100.0 as New
from
    MyTable