1

Can someone help me in getting the cumulative sum and percentage. I have three fields in the table "capability"

vertical|Defects(F)|Defects(NF)|

Billing | 193      |678
Provi   |200       |906
Billing |232       |111
Analyt  |67        |0
Provi   |121       |690

I would want the final output to be

Vertical|Total Defects|Cumulative Defects|Cumulative%

Billing |1214         | 1214             |37.96%
Provi   |1917         | 3131             |97.90%
Analyt  |67           | 3198             |100.00%

Please note that I have around 3mn rows and data keeps increasing day on day.

4

2 回答 2

0

我发现获得累积总和的最简单方法是使用相关子查询——除非您拥有 SQL Server 2012 中的窗口函数的全部功能

然而,这带来了几个挑战。首先,您需要按垂直方向进行总结。然后你需要以正确的顺序排列垂直。最后,您需要以您想要的方式输出结果:

这应该接近你想要的:

with d as
      (select vertical, sum(Defects_N + Defects_NF) as Defects,
              (case when vertical = 'Billing' then 1
                    when vertical = 'Provi' then 2
                    else 3
               end) as num
       from t
       group by vertical
      )
select vertical, defects as TotalDefects, cumDefects,
       100 * cast(cumDefects as float) / fulldefects as DefectPercent
from (select d.*,
             (select sum(defects) from d d2 where d2.num <= d.num
             ) as cumdefects,
             SUM(defects) over () as fulldefects
      from d
     ) d
于 2013-06-10T18:36:05.230 回答
0

好的,这可能会帮助试图获得类似输出的人。这是我为获得所需输出所做的工作。非常感谢戈登,你的建议实际上帮助我使这成为可能

with d as
      (SELECT ROW_NUMBER () OVER  
(ORDER BY SUM([DEFECTS(F)]+[DEFECTS(NF)]) asc) NUM,
VERTICAL,
SUM([DEFECTS(F)]+[DEFECTS(NF)]) AS [DEFECTS]
 FROM Capability
GROUP BY VERTICAL

      )
select left(vertical,5) as Vertical, defects as TotalDefects, cumDefects,
       cast(cumDefects as float) / fulldefects as DefectPercent
from (select d.*,
             (select sum(defects) from d d2 where d2.num <= d.num
             ) as cumdefects,
             SUM(defects) over () as fulldefects
      from d

     ) d
于 2013-06-11T14:40:02.767 回答