加入3个表并添加一个累积百分比的列

时间:2014-08-22 13:23:58

标签: sql sql-server join cumulative-sum

我有3张桌子,我内心相互加入。我添加了一个列,用于计算组合3个表的partcode。我也想

添加一列,其中包含count列的累积过程值。请参阅下面的3个表和查询结果。

Table Test1

 Issue  Code 

 1      11   
 2      12   
 3      13   
 4      14   
 5      15   
 6      16   
 7      17   

Table Test2

 Issue  Code

 1      11   
 2      12   
 4      14   
 5      15   
 6      16




Table Test3

 Code   PartCode

 11     A11      
 12     A12      
 13     A12      
 14     A11      
 15     A11      
 16     A16      
 17     A11      

下一个代码给出如下结果。

SELECT T3.PartCode,
       COUNT(T3.PartCode) AS Number    
FROM Test1 T1 INNER JOIN Test2 T2 ON T1.Issue=T2.Issue   
              INNER JOIN Test3 T3 ON T2.Code=T3.Code    
GROUP BY T3.PartCode   
ORDER BY T3.PartCode

结果:

PartCode  Number  

 A11       3      
 A12       1      
 A16       1    

现在我要添加累积列。然后给出下面的表格作为结果。 如何使用累计的累计百分比创建此列。

Wanted result:
 PartCode  Number  Cumulative precentage 

 A11       3        60                   
 A12       1        80                   
 A16       1       100 

1 个答案:

答案 0 :(得分:1)

假设您的DBMS支持窗口功能:

select ..., sum(100.0*number) over (order by  T3.PartCode) / sum(number) over () as Cumulative_percentage
from ...

编辑:详细阐述了答案

select partcode
     , nbr
     , 100.0*sum(nbr) over (order by partcode) / sum(nbr) over ()
from (
    SELECT T3.PartCode
        , COUNT(*) as nbr
    FROM Test1 T1 
    JOIN Test2 T2 
        ON T1.Issue=T2.Issue   
    JOIN Test3 T3 
        ON T2.Code=T3.Code    
    GROUP BY T3.PartCode  
) as x
ORDER BY PartCode ; 

根据评论更新编辑:

select partcode
     , Description
     , nbr
     , 100.0*sum(nbr) over (order by nbr desc
                                   , partcode) / sum(nbr) over () 
        as Cum_Percentage
from (
    SELECT T3.PartCode
        , T3.Description
        , COUNT(*) as nbr
    FROM Test1 T1 
    JOIN Test2 T2 
        ON T1.Issue=T2.Issue   
    JOIN Test3 T3 
        ON T2.Code=T3.Code    
    GROUP BY T3.PartCode, T3.Description  
) as x
ORDER BY nbr desc;