如何在SQL中显示计数值而不是列出多行?

时间:2014-06-28 03:57:33

标签: sql sql-server

我有三张桌子:考试,目标和考试。

  • 考试可以有零个或多个目标
  • 考试可以有零次或多次测试

我创建了这个SQL来报告数据:

SELECT name, objectiveId, TestId
FROM exam
LEFT JOIN Test ON Test.ExamId = Exam.ExamId
LEFT JOIN Objective ON Objective.ExamId = Exam.ExamId

我想做的不是显示objectiveId和TestId,而是我愿意 想要显示每次考试有多少目标或考试的数量。某物 像:

Exam    Objectives   Tests
Exam1            1      10
Exam2            2       0

1 个答案:

答案 0 :(得分:1)

您可以使用:

SELECT name Exam, COALESCE(COUNT(objectiveId), 0) Objectives, COALESCE(COUNT(TestId), 0) Tests
FROM exam
LEFT JOIN Test ON Test.ExamId = Exam.ExamId
LEFT JOIN Objective ON Objective.ExamId = Exam.ExamId
GROUP BY name;