我試圖執行以下查詢,但我收到一個運行時錯誤,指出單列彙總子查詢的問題:SQL高級查詢 - 在SELECT子句
"The column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause."
線二號下面是一個以上錯誤失敗。我不明白爲什麼這個查詢沒有執行,因爲在第二行中不需要分組,因爲輸出只是count(*),任何線索我需要改變才能使其工作?
SELECT @lessonPlans = COUNT(*)
, @lessonPlanResources = (SELECT COUNT(*) FROM dbo.LessonPlanResource lpr where lpr.LessonPlanId = a.LessonPlanId)
FROM
(
SELECT DISTINCT lpt.LessonPlanId
FROM dbo.LearningTargetBreakout ltb
JOIN dbo.LessonPlanLearningTarget lpt
on lpt.LearningTargetId = ltb.LearningTargetId
WHERE (CASE
WHEN ltb.LearningTargetId = @learningTargetId and @learningTargetId is not null THEN 1
WHEN ltb.CategoryId = @categoryId and @categoryId is not null THEN 1
WHEN ltb.Grade = @grade and @grade is not null THEN 1
WHEN ltb.SubjectId = @subjectId and @subjectId is not null THEN 1
ELSE 0 END) = 1
) a
[編輯]
使用瑞伯的解決方案的細微變化 - 這裏是修改後的代碼,我結束了使用,這將產生一個排,聚集,這是我後。
SELECT @lessonPlans = ISNULL(COUNT(*), 0)
, @lessonPlanResources = ISNULL(SUM(a.ResCount), 0)
FROM
(
SELECT DISTINCT lpt.LessonPlanId, lpr.ResCount
FROM dbo.LearningTargetBreakout ltb
JOIN dbo.LessonPlanLearningTarget lpt
on lpt.LearningTargetId = ltb.LearningTargetId
JOIN (SELECT LessonPlanId, COUNT(*) ResCount FROM dbo.LessonPlanResource lpr GROUP BY LessonPlanId) lpr
ON lpr.LessonPlanId = lpt.LessonPlanId
WHERE (CASE
WHEN ltb.LearningTargetId = @learningTargetId and @learningTargetId is not null THEN 1
WHEN ltb.CategoryId = @categoryId and @categoryId is not null THEN 1
WHEN ltb.GradeId = @grade and @grade is not null THEN 1
WHEN ltb.SubjectId = @subjectId and @subjectId is not null THEN 1
ELSE 0 END) = 1
) a
什麼背後做一個COUNT(*),而不是COUNT(lpr.lessionplanid) – Perpetualcoder 2010-08-05 21:42:35
由於內部查詢的輸出在從你的理由子句只是LessonPlanId字段,如果我沒有弄錯,它實際上和輸入count(lpr.lessionplanid)是一樣的。 – James 2010-08-05 21:53:43