1

我在这里阅读了几个似乎可以回答这个问题的问题,例如如果没有找到行,则返回一个值 SQL

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

在此处输入图像描述

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

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

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


SELECT

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

 cast(s.Year as int) as Year,

CASE r.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,

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


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

FROM Results r
 JOIN Grades g1
  ON r.Result = g1.Grade
LEFT JOIN students s
  ON r.UPN = s.UPN

WHERE r.AcademicYear = @AcademicYear
AND s.AcademicYear = @AcademicYear
AND r.Collection = @Collection
AND SEND = 'Y'

GROUP BY s.Year,
         r.Subject, r.Class

Order by cast(s.year as int) desc, SubjectSort, r.Subject, r.Class, GroupSort
4

1 回答 1

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
于 2018-01-09T21:47:50.473 回答