0

当变量@SubjectName 在“英语”、“数学”和任何其他学科(例如科学)之间更改时,我希望下面的案例语句更改结果集。

When the variable is 'English' the column in students called Ks2en should be included in the results set, but when 'Mathematics' is selected the column changes to Ks2ma and when it is anything else Ks2av should be selected.

如果结果集中有任何空白值 (''),它们将替换为“No KS2”。

这是我到目前为止不起作用的内容:

@SubjectName varchar(100) ='English'

SELECT CASE WHEN (student.Ks2en = '' and @SubjectName = 'English') OR 
    (student.Ks2ma = '' and @SubjectName = 'Mathematics') OR 
    (student.Ks2ma = '' AND @SubjectName <> 'Mathematics' AND
    @SubjectName <> 'English') 
            THEN 'No KS2' ELSE student.ks2en 
                OR student.Ks2ma OR student.Ks2av END AS 'KS2'
  FROM student JOIN subject 
    ON subject.upn=student.upn 
  WHERE
    [subject.Name] = @SubjectName

以下是学生表的示例:

Ks2en    Ks2ma    Ks2av
4b       3c       3a
4a       4a       4a
3c                3c
         2c       2c
4c       3a       4c
4b       4b       4b

5a       3a       4a

因此,当 @SubjectName = 'English' 时,结果集如下所示:

Ks2    
4b       
4a       
3c
No KS2     
4c       
4b
No KS2        
5a           

当@SubjectName = 'Mathematics' 结果集如下所示:

KS2
3c
4a
No KS2
2c
3a
4b
No KS2 
3a

当 @SubjectName = 'Science' 时,结果集如下所示:

KS2
3a
4a
3c
2c
4c
4b
No KS2
4a
4

1 回答 1

1

此代码将根据主题动态返回三列之一。

那是你要的吗?如果需要,您可以在语句末尾添加 where 子句。

约翰

-- dynamically create column
SELECT 
   CASE 
      WHEN lower(coalesce(SubjectName, 'unknown')) = 'english' THEN
        [Ks2en]
      WHEN lower(coalesce(SubjectName, 'unknown')) = 'mathematics' THEN
        [Ks2ma]
      ELSE
        [Ks2av]
   END as KS2
FROM [student] INNER JOIN [subject] ON subject.upn=student.upn 
WHERE [subject].Subjectname LIKE @SubjectName;

我假设您的表架构如下所示。我正在使用元组表示法。

student (upn, student name, ...)
subject (upn, subject name, ks2en, ks2ma, ks2av, ...)

如果不是,代码将无法工作。

于 2013-09-30T15:52:46.667 回答