SQL中的子选择查询不会填充具有特定文本的新列/字段

时间:2017-01-09 22:10:19

标签: mysql sql sql-server sql-server-2008

如何使用“是”或“否”而不是预先存在的数据来填充新字段?在这种情况下,我得到一个名为ESL的新字段,但是如果我用colleagueId填充该字段,我只能运行它。我希望它填充是,而不是真的,我也尝试了案例陈述。

select distinct s.colleagueId,  st.enrollmentStatus, 
s.firstEnrolledTerm,  ESL.colleagueId as ESL

from tbl_studentTerms st

left join

(select distinct colleagueId
from tbl_studentclasses 
where enrolled = 1
and subject = 'ESL') as ESL

on ESL.colleagueId=st.colleagueId


inner join tbl_students s
on st.colleagueId = s.colleagueId
where s.endingCohort = '2009SP' 
and st.term='2009SP'
and s.colleagueId in(select [Student ID] from dbo.pvt_SelectedStudents)

1 个答案:

答案 0 :(得分:1)

这是一种方法:

select distinct s.colleagueId,  st.enrollmentStatus, 
       s.firstEnrolledTerm,
       coalesce(ESL.ESL, 'No') as ESL
from tbl_studentTerms st inner join
     tbl_students s
     on st.colleagueId = s.colleagueId left join
     (select distinct colleagueId, 'Yes' as ESL
      from tbl_studentclasses 
      where enrolled = 1 and subject = 'ESL'
     ) ESL
     on ESL.colleagueId = st.colleagueId 
where s.endingCohort = '2009SP' and st.term = '2009SP' and
      s.colleagueId in (select [Student ID] from dbo.pvt_SelectedStudents);

注意:

  • 我将inner join移到left join之前。我发现最简单的方法是先查询inner join,然后是left join s。
  • 除非您确实需要删除重复项,否则请勿使用select distinct