SQL Server - 强制一行显示在没有值存在的ResultSet中

时间:2017-12-11 10:37:05

标签: sql sql-server null coalesce

我试图找到一种强制行显示在输出结果集中的方法,即使没有找到值也是如此。我可能使用COALESCE处于正确的位置,但我无法确定查询中需要的位置。

我尝试了几个地方,但没有成功。到目前为止,我的代码如下。

因此,对于下面的代码,它会返回一个主题的行,其中结果的学​​生的SEND设置为'Y',但是没有显示没有学生结果的行SEND设置为'N'的主题。但是,我希望显示一行用于格式化,因此无论是否有结果的SEND学生,输出结果集的大小始终相同。

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

SELECT
 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,
  5 AS GroupSort, Class, Teacher,
  'SEND (' + CAST(COUNT(g1.Points) AS varchar) + ')' AS 'Group',

  COALESCE(Count(1),0)  AS 'No. Girls',

  --4+
  SUM(CASE
    WHEN g1.Points >= 4 THEN 1
    ELSE 0
  END) AS 'No. 4+/A*-C',
  CAST(SUM(CASE
    WHEN g1.Points >= 4 THEN 1
    ELSE 0
  END) AS decimal) / COUNT(g2.Points) AS '% 4+/A*-C',
  --5+
  SUM(CASE
    WHEN g1.Points >= 5 THEN 1
    ELSE 0
  END) AS 'No. 5+/A*-B',
  CAST(SUM(CASE
    WHEN g1.Points >= 5 THEN 1
    ELSE 0
  END) AS decimal) / COUNT(g1.Points) AS '% 5+/A*-B',
  --7+
  SUM(CASE
    WHEN g1.Points >= 7 THEN 1
    ELSE 0
  END) AS 'No. 7+/A*-A',
  CAST(SUM(CASE
    WHEN g1.Points >= 7 THEN 1
    ELSE 0
  END) AS decimal) / COUNT(g1.Points) AS '% 7+/A*-A'

FROM Results r
JOIN Grades g1
  ON r.Result = g1.Grade
INNER JOIN Grades g2
  ON r.Target = g2.Grade
INNER JOIN Grades g3
  ON r.Prediction = g3.Grade 
INNER JOIN Grades g4 
  ON r.Mock = g4.Grade 
INNER JOIN students s
  ON r.UPN = s.UPN

WHERE r.AcademicYear = @AcademicYear
AND s.AcademicYear = @AcademicYear
AND r.Collection = @Collection
AND COALESCE(SEND,'') = 'Y'

GROUP BY Year, Class, Teacher,
         Subject

Order by SubjectSort, Subject, Class, Teacher, GroupSort

1 个答案:

答案 0 :(得分:0)

这样的事情:

declare @t table(name varchar(100));
insert into @t values ('Paul'), ('Jane'), ('Mary');

declare @param varchar(100) = 'Sean'--'Paul';

select *
from @t
where name = @param

union all

select 'no name found'
where not exists(select *
                from @t
                where name = @param
                 );

取消注释现有名称,并查看表格中的行是如何返回的;如果没有与您的参数匹配的行,则会返回“找不到名字”。