我正在爲連接三個表的報表頁編寫sql代碼。這是我寫的查詢。在表中使用COUNT函數加入
comm.CommandText = "SELECT Count(DISTINCT Courses.CourseID) AS CourseCount, Count(DISTINCT Students.StudentID) AS StudentCount, Count(Students.StartDate) AS StartCount, School.Name, School.StartDate, School.SchoolFees " +
"FROM Schools " +
"LEFT JOIN Courses ON (School.SchoolID = Courses.SchoolId) " +
"LEFT JOIN Students ON (School.SchoolID = Student.SchoolID) " +
"WHERE School.Active = 1 " +
"GROUP BY School.Name, School.StartDate, School.SchoolFees";
以上查詢效果很好。但是我想顯示Student.StartDate滿足條件的每個School的Student.StartDate的計數。下面是我想用
SELECT Count(Students.StartDate)
FROM Students
WHERE Student.StartDate >= DATEADD(month, -1, GETDATE());
我想上面的查詢被返回作爲我的主要查詢的一部分,但不知道如何實現查詢。任何幫助將不勝感激。謝謝
您的回答非常有用和信息豐富。我學到了一些新東西。非常感謝。我有一個小問題。當擺脫COALESCE表達式,這是否意味着我只有「SELECT CourseCount,StudentCount .....」。 – elfico
@elfico:確實。從不同表格中選擇數據時,我使用表格限定符來顯示列的起始位置 - 即使列名稱應足夠描述:「SELECT c.CourseCount,s.StudentCount,s.StartCount ...」 –