Thursday, May 5, 2011

select max data from multiple column with respect id using PIVOT in SQL SERVER

Sometimes , we face a problem , how can retrive a max data from multiple column.
suppose ,  i have a table of student result.
In this table multiple column , ie, ROLLNUMBER , MATH,PHYSICS,CHEMISTRY ,TOTALMARKS.
it can be easilly calculated what is his  TOTALMARKS , but it cam be tuff , in which subject he got maximum marks??

Try some dummy code as follow
////////////////////TABLE CREATE////////////////////////////////////////////
CREATE TABLE [dbo].[TBLRESULT]([ROLLNUMBER] [bigint] NOT NULL,[MATH] [int] NULL,[PHYSICS] [int] NULL,[CHEMISTRY] [int]
)
NULL ON [PRIMARY]

//////////////////////////////INSERT DATA    START QUERY////////////////////////////////////////
INSERT INTO TBLRESULT VALUES(ROLLNUMBER,MARKSOFmaths,MARKSOFphysics,MARKSOFchemistry)

 EXAMPLE --
  INSERT  INTO TBLRESULT VALUES(1004,12,0,9)

///////////////////////////////END QUERY///////////////////////////////////////////

SELECT *  FROM TBLRESULT


ROLLNUMBERMATHPHYSICSCHEMISTRY
1001101214
1002101412
100314120



Now use this query

////////////////////////////START QUERY//////////////////////////////////////////////////////////////

select row_number()over(partition by ROLLNUMBER order by MAXMARKS desc) as MAXMARKSID,ROLLNUMBER , SUBJECTS,MAXMARKSfrom (select ROLLNUMBER,SUBJECTS,MAXMARKS from (select ROLLNUMBER,MATH,PHYSICS,CHEMISTRY from TBLRESULT) ALIAS1unpivot
(
MAXMARKS for SUBJECTS in(MATH,PHYSICS,CHEMISTRY)) AS ALIAS2 ) ALIAS3



////////////////////////////////END QUERY/////////////////////////////////////////////////////

Result like this
 

MAXMARKSIDROLLNUMBER MAXMARKSMARKS
1100114CHEMISTRY
2100112PHYSICS
3100110MATH
1100214PHYSICS
2100212CHEMISTRY
3100210MATH
1100314MATH
2100312PHYSICS
310030CHEMISTRY
1100412MATH
210049CHEMISTRY
310040PHYSICS



Now for Mximum obtained marks subjec can be obtained as


///////////////////////////START QUERY/////////////////////////////////////////////////////////////////////////////

WITH DUMMYTABLE as (select row_number()over(partition by ROLLNUMBER order by MAXMARKS desc) as MAXMARKSID,ROLLNUMBER , SUBJECTS,MAXMARKSfrom (select ROLLNUMBER,SUBJECTS,MAXMARKS from (select ROLLNUMBER,MATH,PHYSICS,CHEMISTRY from TBLRESULT) ALIAS1unpivot
(
MAXMARKS for SUBJECTS in(MATH,PHYSICS,CHEMISTRY)) AS ALIAS2 ) ALIAS3)select ROLLNUMBER,SUBJECTS,MAXMARKS from DUMMYTABLE where DUMMYTABLE.MAXMARKSID =1

////////////////////////////////////////////END QUERY//////////////////////////////////////////////////////////////////
Result like this



ROLLNUMBER SUBJECTSMAXMARKS
1001CHEMISTRY14
1002PHYSICS14
1003MATH14




No comments:

Post a Comment