根据条件声明变量

时间:2017-05-22 14:22:40

标签: sql

我想声明变量@Grade:

Declare @Grade varchar(max)''
Select @Grade = ...

连接表需要满足以下条件:

如果tableA id中存在table1 subjectid,则从tableA为每个studentntid选择@Grade

如果tableB idjectid存在于tableB id中,则从tableB为每个studentntid选择@Grade

如果tableC subjectid存在于tableC id中,则从tableC为每个studentid选择@Grade

Sample Table1 - Student
Student ID   Subject ID   Rating
100          200          A
101          200          B
102          300          A
103          400          B
104
105          300          A

Sample TableA - Chinese
Subject ID  Rating      Grade
200         A           Good
200         B           Poor

Sample TableB - English
Subject ID  Rating       Grade
300         A            Good
300         B            Poor

Sample TableC - Maths
Subject ID  Rating       Grade
400         A            Good
400         B            Poor

Expected output:
Student ID   Subject ID   @Grade
100          200          Good
101          200          Poor
102          300          Good
103          400          Poor
104
105          300          Good

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

这似乎产生了您的预期结果:

declare @Student table (StudentID int not null,SubjectID int null,Rating char(1) null)
insert into @Student(StudentID,SubjectID,Rating) values
(100,200 ,'A'),    (101,200 ,'B'),    (102,300 ,'A'),
(103,400 ,'B'),    (104,null,null),    (105,300 ,'A')

declare @Chinese table (SubjectID int not null,Rating char(1) not null,Grade varchar(17) not null)
insert into @Chinese(SubjectID,Rating,Grade) values
(200,'A','Good'),    (200,'B','Poor')

declare @English table (SubjectID int not null,Rating char(1) not null,Grade varchar(17) not null)
insert into @English(SubjectID,Rating,Grade) values
(300,'A','Good'),    (300,'B','Poor')

declare @Maths table (SubjectID int not null,Rating char(1) not null,Grade varchar(17) not null)
insert into @Maths(SubjectID,Rating,Grade) values
(400,'A','Good'),    (400,'B','Poor')

select
    s.StudentID,
    s.SubjectID,
    COALESCE(c.Grade,e.Grade,m.Grade) as Grade
from
    @Student s
        left join
    @Chinese c
        on
            s.SubjectID = c.SubjectID and s.Rating = c.Rating
        left join
    @English e
        on
            s.SubjectID = e.SubjectID and s.Rating = e.Rating
        left join
    @Maths m
        on
            s.SubjectID = m.SubjectID and s.Rating = m.Rating

结果:

StudentID   SubjectID   Grade
----------- ----------- -----------------
100         200         Good
101         200         Poor
102         300         Good
103         400         Poor
104         NULL        NULL
105         300         Good

请注意,您当前的表设计对我们没有帮助 - 我不清楚为什么我们为主题标记方案设置了三个单独的表 - 所有数据看起来都像是出现在一个表中这将大大简化上述查询。