Home Forums SQL Server 2008 T-SQL (SS2K8) Retrives the subject wise highest marks list in a table RE: Retrives the subject wise highest marks list in a table

  • Check Below SQL and let me know if it's work for you

    use tempdb;

    go

    create table stu( id int , name varchar(10))

    insert into stu(id,name)

    select 1 id, 'x' name union all

    select 2, 'y' union all

    select 3 , 'z' union all

    select 4, 'a' union all

    select 5, 'b'

    create table mark(id int ,maths int, physics int ,English int)

    insert into mark

    select 1, 50, 60, 70 union all

    select 2 ,70 ,60, 40 union all

    select 3, 50, 80, 70 union all

    select 4 ,50 ,100, 70 union all

    select 5 ,90, 60, 70

    go

    SELECT id,

    subject,

    MARK,

    Row_number() OVER ( ORDER BY id, MARK DESC ) AS row_id

    into #t

    FROM

    (SELECT id,

    Convert(VARCHAR(15), subject) [subject],

    MARK

    FROM

    (SELECT id,

    maths,

    physics,

    english

    FROM

    MARK) p UNPIVOT (MARK FOR [subject] IN (maths, physics, english) )AS unpvt) t

    GO

    SELECT t.*

    FROM

    #t t

    INNER JOIN (SELECT id,

    Min(row_id) row_id

    FROM

    #t

    GROUP BY id)tt

    ON t.row_id = tt.row_id