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

  • An effective method is a CROSS APPLY VALUES UNPIVOT (described in my signature links):

    WITH Students (id, studname) AS

    (

    SELECT 1, 'x'

    UNION ALL SELECT 2, 'y'

    UNION ALL SELECT 3, 'z'

    UNION ALL SELECT 4, 'a'

    UNION ALL SELECT 5, 'b'

    ),

    Markslist (id, maths, physics, English) AS

    (

    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

    )

    SELECT studname, [subject], score

    FROM

    (

    SELECT studname, [subject], score

    ,rn=ROW_NUMBER() OVER (PARTITION BY [subject] ORDER BY score DESC)

    FROM Students a

    JOIN MarksList b ON a.id = b.id

    CROSS APPLY

    (

    VALUES (maths, 'maths'), (physics, 'physics'), (English, 'English')

    ) c (score, [subject])

    ) a

    WHERE rn=1;

    Using ROW_NUMBER() instead of GROUP BY will even tell you the "stud" whose name got the high score.

    If there's a tie for high score and you want to show that, use RANK() instead of ROW_NUMBER().


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St