Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 query help

Author  Topic 

sqlfresher2k7
Aged Yak Warrior

623 Posts

Posted - 2014-12-27 : 20:46:58
[code]

Please help to rewrite the below query to get the expected output..
I want the description if exist for student to be 1 else 0..


Query
-------

Select
StudentNo,
Name,
Science,
Social,
Math
From
StudentInfo Sinfo Left Join StudentDesc SDesc
On Sinfo.StudentNo = SDesc.StudentNo
where SDesc.Desc in ('Science','Social','Math')



Table:StudentInfo

StudentNo Name
-------- -------
1234 Sam
1235 Brad
1236 Viv
1237 Brigg
1241 Sim



Table:StudentDesc

StudentNo Desc
--------- -----
1234 Science
1235 Social
1236 Science
1237 Math
1238 Math
1239 English
1240 English


Expected output
==================


StudentNo Name Science Social Math
-------- ------- -------- ------- ------
1234 Sam 1 0 0
1235 Brad 0 1 0
1236 Viv 1 0 1
1237 Brigg 0 0 1
1241 Sim 0 0 0




[/code]

sqlteamsam
Starting Member

1 Post

Posted - 2014-12-28 : 06:37:04
pls try this


Select StudentNo,Name,
case when Science is null then 0 else 1 end ,
case when Social is null then 0 else 1 end,
case when Math is null then 0 else 1 end,
From
StudentInfo Sinfo Left Join StudentDesc SDesc
On Sinfo.StudentNo = SDesc.StudentNo
where SDesc.Desc in ('Science','Social','Math')
Go to Top of Page
   

- Advertisement -