问题
I would like the below case statement to change the resultset when the variable @SubjectName is changed between 'English', 'Mathematics' and any other subject eg science.
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.
Where there are any blank values ('') in the results set they are replaced with 'No KS2'.
Here is what I have so far which doesn't work:
@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
Here is an example of the student table:
Ks2en Ks2ma Ks2av
4b 3c 3a
4a 4a 4a
3c 3c
2c 2c
4c 3a 4c
4b 4b 4b
5a 3a 4a
So when @SubjectName = 'English' the result set looks like:
Ks2
4b
4a
3c
No KS2
4c
4b
No KS2
5a
And when @SubjectName = 'Mathematics' the result set looks like:
KS2
3c
4a
No KS2
2c
3a
4b
No KS2
3a
And when @SubjectName = 'Science' the result set looks like:
KS2
3a
4a
3c
2c
4c
4b
No KS2
4a
回答1:
This code will dynamically return one of three columns depending upon subject.
Is that what you want? You can tack you where clause at the end of the statement if needed.
John
-- 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;
I am assuming your table schema is like the following. I am using tuple notation.
student (upn, student name, ...)
subject (upn, subject name, ks2en, ks2ma, ks2av, ...)
If it is not, the code will not work.
来源:https://stackoverflow.com/questions/19098398/sql-conditional-statement-in-group-by-clause