如何在SQL Server 2005中找到Pivoting两列的Sum?

时间:2012-06-15 03:49:47

标签: sql-server-2005 find sum pivot

我使用以下程序通过使用透视查询来检索总presentsabsents ....我想要SUMPresents[P] Absents[A]然后calculate percentage

ALTER PROCEDURE [dbo]。[GetAttendence](@ Course_Id varchar(30),@ Semester varchar(10))

AS
   SELECT DISTINCT Enroll_Number, Course_Id, Semester, Isnull([P],0) 
                                           As Presents, Isnull([A],0) As Absents

    FROM (SELECT Enroll_Number, Course_Id, Semester, Flag from Attendence ) ps
    pivot(Count(Flag) for Flag in ([P],[A])) as pvt 

    WHERE Course_Id = @Course_Id and Semester = @Semester

这是Forula来实现....

Sum = Presents + Absents

百分比=((礼物/总和)* 100)

1 个答案:

答案 0 :(得分:0)

试试这个:

select Enroll_Number,
       Course_Id,
       Semester,
       P as Presents,
       A as Absents,
       P+A as SumPA,
       1.0*P/(P+A)*100 as Percentage
from
  (
    select Enroll_Number, Course_Id, Semester, Flag
    from Attendence
    where Course_Id = @Course_Id and 
          Semester = @Semester
  ) ps
pivot
  (
    count(Flag) for Flag in ([P],[A])
  ) as pvt