2016-05-05 49 views
1

我想在asp.net中生成一個sql server數據庫的報告,我得到一些列作爲兩列產品的結果。下面是代碼Sql加入多列表返回兩列的產品

comm.CommandText = "SELECT Count(Courses.CourseID) AS CourseCount, Count(Students.StudentID) AS StudentCount, Schools.Name, Schools.StartDate, Schools.SchoolFees " + 
       "FROM Schools" + 
       "LEFT JOIN Courses ON (Schools.SchoolID = Courses.SchoolID)" + 
       "LEFT JOIN Students ON (Schools.SchoolID = Students.SchoolID) " + 
       "WHERE Schools.Active = 1 " + 
       "GROUP BY Schools.Name, Schools.StartDate, Schools.SchoolFees"; 

當運行的代碼,其結果顯示,但對於「CourseCount」和「StudentCount」的列顯示一個值,該值是每個單獨的柱的產物。 「CourseCount」通常是288,「StudentCount」是38,但是當我運行代碼時,「CourseCount」和「StudentCount」顯示10944爲38 x 288.

無論如何,我可以讓他們顯示正確的值?

回答

3

使用所有行數,以不同值的數改變你的代碼而已,應該返回你期望返回

comm.CommandText = "SELECT Count(DISTINCT Courses.CourseID) AS CourseCount, Count(DISTINCT Students.StudentID) AS StudentCount, Schools.Name, Schools.StartDate, Schools.SchoolFees " + 
      "FROM Schools" + 
      "LEFT JOIN Courses ON (Schools.SchoolID = Courses.SchoolID)" + 
      "LEFT JOIN Students ON (Schools.SchoolID = Students.SchoolID) " + 
      "WHERE Schools.Active = 1 " + 
      "GROUP BY Schools.Name, Schools.StartDate, Schools.SchoolFees"; 

的結果是技術上是正確的,如果所有的學校都有課程的結果,並且所有課程都有學生

+0

效果很好!非常感謝@rossquan。 – elfico

0

如上所述,您是如何使用COUNT(),您是要求它計算所有,這就是爲什麼它返回這麼多。只需計算您想要計算的兩個值即可使用計數。

0

這可能表現比重複計數方法越好..

comm.CommandText = 
    "SELECT cc.CourseCount, sc.StudentCount, Schools.Name, Schools.StartDate, Schools.SchoolFees " + 
    "FROM Schools" + 
    "OUTER APPLY (SELECT Count(Students.StudentID) StudentCount FROM Students WHERE Students.SchoolID = Schools.SchoolID) sc " + 
    "OUTER APPLY (SELECT Count(Courses.CourseID) CourseCount FROM Courses WHERE Courses.SchoolID = Schools.SchoolID) cc " + 
    "WHERE Schools.Active = 1 ";