2016-04-03 74 views
0
SELECT 

subj.SubjectID   AS [ID], 
subj.SubjectDescription AS [Subject], 
enrol.StuSubjEnrolmentID AS [IsEnrol] 


FROM [PATHWAYS].[Subjects] AS [subj] 

LEFT JOIN 
[STUDENT].[StuSubjEnrolment] AS [enrol] 
ON subj.SubjectID = enrol.SubjectID 

LEFT JOIN 
[STUDENT].[Student] AS [stu] 
ON enrol.StuID = stu.StuID 
AND stu.StuID = @stuID 

傢伙嗨,任何人都可以請指導我這個?先謝謝你。我對此很無能。SQL - 如果Else裏面的返回值?

我怎麼能寫的方式,這種說法....

IsEnrol不爲空,則返回0否則返回1?我想那個特定的列,只顯示1或0

+1

嘗試使用CASE表達式 – Dejan

+0

你希望每個IsEnrol行爲1或0,如果它是NULL /非NULL?存儲過程如何進入這個過程? – iliketocode

+1

[如何在SQL SELECT中執行IF ... THEN]可能的重複?(http://stackoverflow.com/questions/63447/how-to-perform-an-if-then-in-an-sql - 請選擇) –

回答

1

試試這個

SELECT 

subj.SubjectID   AS [ID], 
subj.SubjectDescription AS [Subject], 
CASE WHEN enrol.StuSubjEnrolmentID is not null then 0 else 1 end as AS [IsEnrol] 

FROM [PATHWAYS].[Subjects] AS [subj] 
LEFT JOIN [STUDENT].[StuSubjEnrolment] AS [enrol] 
ON subj.SubjectID = enrol.SubjectID 
LEFT JOIN [STUDENT].[Student] AS [stu] 
ON enrol.StuID = stu.StuID 
AND stu.StuID = @stuID 
+0

非常感謝。這就是答案:D – DriLLFreAK100

1

假設你正在使用SQL Server 2012或更高版本,可以使用IIF功能 -

SELECT 

subj.SubjectID   AS [ID], 
subj.SubjectDescription AS [Subject], 
iif(enrol.StuSubjEnrolmentID is null,1,0) AS [IsEnrol] 


FROM [PATHWAYS].[Subjects] AS [subj] 

LEFT JOIN 
[STUDENT].[StuSubjEnrolment] AS [enrol] 
ON subj.SubjectID = enrol.SubjectID 

LEFT JOIN 
[STUDENT].[Student] AS [stu] 
ON enrol.StuID = stu.StuID 
AND stu.StuID = @stuID 

如果您正在使用早於2012年的SQL Server版本,那麼@ dejan87的帖子中的Case聲明方法將是最佳解決方案。