Assistance with PIVOT

  • I have looked through many examples on the web for PIVOT commands, but am still struggling to find the right way of doing it. Its probably somehitng really simple that i am missing, but if you could help me that would be great πŸ™‚

    I am creating a database to handle ranking points for Badminton, and have created a table with the following structure:

    create table tempstore(

    tmp_agegrp varchar(5), -- age group of the players U12 / U14 etc

    tmp_event varchar(5), -- event type MS, WS, MD, WD, XD

    tmp_event_id numeric (3,0), -- Event code (numeric which is a FK to the events table)

    tmp_playerno numeric (5,0), -- Unique player number (numeric which is a FK to the players table)

    tmp_points numeric (5,0) -- ranking points obtained in that event.

    )

    the format that has been requested by my provincial body is:

    Age_group Event Player_number Event1 Event2 Total

    U12 MS 1 100 100 200

    etc.

    All the examples i have seen online tend to have one field as the key on the left side, where as here i have 3 (age, event, playernumber) and this is where i am having problems as i cant seem to find the right syntax in the TSQL to merge these together.

    As i said, might be something stupidly simple that i am missing, but its gone midnight now and brain is shutting down!

    If anyone has done anything similar and would like to share their code your help would be very much appreciated before i resort to manual extracts and EXCEL VLOOKUPS! πŸ™‚

    Thanks in advance.

  • Hi Mark, this looks like a straightforward CROSSTAB query. Have a quick read of this article [/url]which will show you how to set up a few rows of sample data. You can read about crosstab queries here[/url].

    β€œWrite the query the simplest way. If through testing it becomes clear that the performance is inadequate, consider alternative query forms.” - Gail Shaw

    For fast, accurate and documented assistance in answering your questions, please read this article.
    Understanding and using APPLY, (I) and (II) Paul White
    Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden

  • Thanks for the tip Chris, I have never come across the CASE command before.

    was easy in the end πŸ™‚

    select r.r_age_group, r.r_event, p.firstname + ' ' + p.surname,

    sum(case when r.r_event_id=1 then r.r_points else 0 END) as 'Event1',

    sum(case when r.r_event_id=2 then r.r_points else 0 END) as 'Event2',

    sum(r.r_points) as 'Total'

    from results r, player p

    where r.r_player_number = p.player_number

    group by r.r_age_group, r.r_event, p.firstname + ' ' + p.surname

    order by r.r_age_group, r.r_event, total desc

    Thanks again πŸ™‚

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply