I have a page where I am running an initial SQL query to get a list of subjects, then I loop over this query and run two additional queries for each record returned from the original subjects query (I happen to be doing this in ColdFusion, but not sure that really matters). These two additional queries do COUNTs for that specific subject and then output the results (print the Subject name, then the two counts for that subject). I was trying to improve performance for this page, and wanted to know if I could somehow combine this into a single query.
Initial Query:
SELECT subject_ID, subject_name FROM Subjects ORDER BY subject_name
Queries inside the loop of the initial query:
SELECT COUNT(test_ID) as priority_count FROM Test_Queue WHERE priority_flag = 1 AND subject_ID = #SubjectQuery.subject_ID# SELECT COUNT(test_ID) as locked_count FROM Test_Queue WHERE locked = 1 AND subject_ID = #SubjectQuery.subject_ID#
Suggestions on how these might be optimized? DB is MS SQL 2008. Thanks.