在没有值存在的结果集中显示行

时间:2018-01-09 21:43:37

标签: sql sql-server null nullif

我在这里读了几个问题似乎回答了这个问题,例如: Return a value if no rows are found SQL

然而,我正努力让它为我工作。这是我查询的输出:

enter image description here

作为一个例子,实际上有六个类,但只有三个显示,因为它们实际上有结果。我希望没有结果的类也可以在No. Other列中显示空值。

到目前为止,这是我的代码:

12345.1

1 个答案:

答案 0 :(得分:0)

当您使用JOIN时,假设它是内部联接,并且内部联接不包括在成绩表中没有项目的结果。只需将其设为左连接:

DECLARE @AcademicYear varchar(9) = '2017/2018',
        @Collection varchar(50) = 'Autumn';


SELECT

Test = NULLIF(COUNT(g1.Points),0),

 cast(Year as int) as Year,

CASE Subject
    WHEN 'English' THEN 1
    WHEN 'English Language' THEN 2
    WHEN 'English Literature' THEN 3
    WHEN 'Maths' THEN 4
    WHEN 'Science' THEN 5
    WHEN 'Additional Science' THEN 6
    WHEN 'Biology' THEN 7
    WHEN 'Chemistry' THEN 8
    WHEN 'Physics' THEN 9
    WHEN 'Arabic' THEN 10
    WHEN 'Dutch' THEN 11
    WHEN 'French' THEN 12
    WHEN 'Russian' THEN 13
    WHEN 'Spanish' THEN 14
    WHEN 'Urdu' THEN 15
    ELSE 16
  END AS SubjectSort,

  Subject, Class, 
  0 AS GroupSort,
'SEND (' + CAST(COUNT(g1.Points) AS varchar) + ')' AS 'Group',


    --Other
 SUM(CASE
    WHEN Progress in ('X','Abs','New') THEN 1
    ELSE 0
  END) AS 'No. Other'

FROM Results r
LEFT JOIN Grades g1
  ON r.Result = g1.Grade
LEFT JOIN students s
  ON r.UPN = s.UPN AND s.SEND = 'Y' AND s.AcademicYear = @AcademicYear

WHERE r.AcademicYear = @AcademicYear
    AND r.Collection = @Collection


GROUP BY Year,
         Subject, Class

Order by cast(year as int) desc, SubjectSort, Subject, Class, GroupSort