2017-04-06 47 views
0

如何獲得除以SQL Server 2014中最後四個值的值?SQL Server:值除以最後四個值的滾動和?


例子。如何從Value字段獲得ValueDIVbyLastFourValues字段?

Month|Value| ValueDIVbyLastFourValues | 
--------------------------------------- 
    1 | 1 |   1    | 
    2 | 1 |   1/2   | 
    3 | 2 |   2/4   | 
    4 | 2 |   2/6   | 
    5 | 1 |   1/6   | 
    6 | 7 |   7/12   | 
    7 | 4 |   4/14   | 

壞試用

SELECT 
    CUSTOMER 
    ,MONTH 
    ,NET_VALUE_M/SUM(NET_VALUE_M) AS 'NET_VALUE_M_PROP_BY_YEAR' 
FROM 
    MY DATA 
GROUP BY LEFT(MONTH,4) 
     ,CUSTOMER 
     ,MONTH 
     ,NET_VALUE_M 
ORDER BY NET_VALUE_M_PROP_BY_YEAR 

回答

1

如果我理解正確:

SELECT CUSTOMER, MONTH, 
     (NET_VALUE_M/
     SUM(NET_VALUE_M) OVER (ORDER BY MONTH ROWS BETWEEN 4 PRECEDING AND CURRENT ROW) 
     ) AS NET_VALUE_M_PROP_BY_YEAR 
FROM MY DATA; 

它使用窗函數來概括當前行中的值和前四排。

相關問題