2013-07-15 23 views
0

我有一張表格,表示所有學生必須參加10門課程,其中5個是強制性的,從其他5個選擇3個。所以基本上有2個組。現在我需要計算總積分和總積分總和。在同一查詢中具有不同範圍的多重求和功能


表#1

 StudentID ProgID ProgName GroupID GroupName Course Complete_Courses_Alert Credits 
      1   100 MS  501  Mandatory 12  Remaining   3 
      1   100 MS  501  Mandatory 13  Complete   3 
      1   100 MS  501  Mandatory 14  Complete   3 
      1   100 MS  501  Mandatory 15  Remaining   3 
      1   100 MS  501  Mandatory 16  Complete   3 
      1   100 MS  502  Elective 17  Complete   3 
      1   100 MS  502  Elective 18  Complete   3 
      1   100 MS  502  Elective 19  Remaining   3 
      1   100 MS  502  Elective 20  Complete   3 
      1   100 MS  502  Elective 21  Remaining   3 

我想要的輸出作爲

上表中,但更添加到它2個字段。

完成學分的,即總和(總學分) 和點心完成學分(按組)

這是我迄今所做的, 我創建了一個視圖計算總學分和GrouptotalCredits然後joinin它在主查詢上。這樣我再次需要創建另一個視圖來執行更多的查詢功能..

任何人都可以幫忙。

回答

1

我認爲你正在尋找的東西,如:

select * 
    , StudentGroupCredits = sum(case when Complete_Courses_Alert = 'Complete' then Credits else 0 end) over (partition by StudentId, GroupName) 
    , StudentTotalCredits = sum(case when Complete_Courses_Alert = 'Complete' then Credits else 0 end) over (partition by StudentId) 
from Courses 

SQL Fiddle with demo

在Books Online查看OVER Clause瞭解更多信息。

+0

上述查詢按照組和按程序添加所有學分,但不會爲已完成的課程添加。 –

+0

我已經更新了查詢,只將「完成」行添加到兩個總計中;這是否更好? –

+0

非常感謝伊恩。它完美的作品。試圖創建一個視圖來做到這一點。您是否隨時使用物化視圖。如果是,請告訴我它是如何工作的。非常感謝您 –

相關問題