question

Madhubose avatar image
Madhubose asked

What would be the best query to get requested output?

use tempdb go set nocount on if object_id('tempdb ..#sem01') is not null drop table tempdb ..#sem01 create TABLE #sem01 (StudentID INT, majorsubject VARCHAR(20)) INSERT INTO #sem01(StudentID, majorsubject) SELECT 1,'Physics' INSERT INTO #sem01(StudentID, majorsubject) SELECT 2,'Chemistry' INSERT INTO #sem01(StudentID, majorsubject) SELECT 3,'Maths' if object_id('tempdb ..#sem02') is not null drop table tempdb ..#sem02 create TABLE #sem02 (StudentID INT, minorsubject VARCHAR(20)) INSERT INTO #sem02(StudentID, minorsubject) SELECT 1,'Biology' INSERT INTO #sem02(StudentID, minorsubject) SELECT 1,'Computer Science' INSERT INTO #sem02(StudentID, minorsubject) SELECT 2,'Botany' INSERT INTO #sem02(StudentID, minorsubject) SELECT 2,'Zoology' if object_id('tempdb ..#sem03') is not null drop table tempdb ..#sem03 create TABLE #sem03 (StudentID INT, optional VARCHAR(20)) INSERT INTO #sem03(StudentID, optional) SELECT 1,'Environment' INSERT INTO #sem03(StudentID, optional) SELECT 1,'Sanskrit' INSERT INTO #sem03(StudentID, optional) SELECT 1,'GK' INSERT INTO #sem03(StudentID, optional) SELECT 2,'History' select * from #sem01 /* StudentID majorsubject 1 Physics 2 Chemistry 3 Maths */ select * from #sem02 /* StudentID minorsubject 1 Biology 1 Computer Science 2 Botany 2 Zoology */ select * from #sem03 /* StudentID optional 1 Environment 1 Sanskrit 1 GK 2 History */ **--** Output Required** /* StudentID majorsubject minorsubject Optional 1 Physics Biology Environment 1 Physics Computer Science Sanskrit 1 Physics NULL GK 2 Chemistry Botany History 2 Chemistry Zoology NULL 3 Maths NULL NULL */ --=================================================================
tempdbtemporary-tables
3 comments
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Magnus Ahlkvist avatar image Magnus Ahlkvist commented ·
Is that all the information you have? If there's no relation between majorsubject, minorsubject and optional, then there is no way to work out which majorsubject goes along with which minorsubject and/or optional. How would you otherwise know that Sanskrit goes along with Physics and Computer Science, or that Physics has no minorsubject and GK as optional for studentID=1?
5 Likes 5 ·
ThomasRushton avatar image ThomasRushton ♦♦ commented ·
@Madhubose - what have you tried so far? What's not working for you?
2 Likes 2 ·
ThomasRushton avatar image ThomasRushton ♦♦ commented ·
Indeed. +1 to what @Magnus Ahlkvist said. However, if there's no intended link between the major & minor, then also let us know!
0 Likes 0 ·

0 Answers

·

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.