每个状态平均值的SQL查询计算列

时间:2016-10-25 04:43:35

标签: sql sql-server sql-server-2008 select subquery

这是我的桌子。

   Fund   Industry State    
     1        2      NSW             
     1        2      ACT         
     1        2      VIC          
     1        2      NSW         
     1        2      ACT         
     1        2      VIC         
     1        2      NSW          
     1        2      ACT         
     1        2      VIC      

我要进行三次计算。以下是计算列

Fund   Industry State  Column1  Column2  Column3  
 1        2      NSW      5       10        
 1        2      ACT      5       10      
 1        2      VIC      5       10      
 1        2      NSW      5       10      
 1        2      ACT      5       10      
 1        2      VIC      5       10      
 1        2      NSW      5       10      
 1        2      ACT      5       10      
 1        2      VIC      5       10          

我计算了column1 as Fund*5Column2 as Industry*5Column3 is the average of Column1 per state。i,e

NSW is (5+5+5)/3
ACT is (5+5+5)/3
VIC is (5+5+5)/3

决赛桌将是

Fund   Industry State  Column1  Column2  Column3  
 1        2      NSW      5       10        5
 1        2      ACT      5       10        5
 1        2      VIC      5       10        5
 1        2      NSW      5       10        5
 1        2      ACT      5       10        5
 1        2      VIC      5       10        5
 1        2      NSW      5       10        5
 1        2      ACT      5       10        5
 1        2      VIC      5       10        5

我可以计算column1column2,但不知道如何计算column3

Select distinct Fund, Industry, State, Fund * 5 as Column1, Industry * 5 as Column2 
from fundDetails

任何帮助将不胜感激。提前致谢

1 个答案:

答案 0 :(得分:2)

您可以在窗口函数中使用AVG

SELECT Fund,
       Industry,
       State,
       Fund * 5 AS Column1,
       Industry * 5 AS Column2,
       AVG(Fund*5) OVER (PARTITION BY State) AS Column3
FROM fundDetails