Pivot in SQL

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • codepirate
    New Member
    • May 2007
    • 7

    Pivot in SQL

    I have query that returns results like the following:

    request_id field_id field_value
    12345 2 abc
    12345 3 asdf
    12345 11 10
    12346 2 def
    12346 3 asdf
    12346 11 20

    and so on.
    I would like to display the results like this:

    request_id field_2 field_3 field_11
    12345 abc asdf 10
    12346 def asdf 20

    I tried the floowing "pivot" command in SQL 2005:

    select request_id, field_id, field_value
    from some_table
    pivot (
    field_value for field_id in (2, 3, 11)
    )

    but I keep getting this error:

    Error in FROM clause: near 'FOR'.
    Unable to parse query text.

    Does anyone have any idea what I am doing wrong?
    Thanks in advance.
  • ck9663
    Recognized Expert Specialist
    • Jun 2007
    • 2878

    #2
    Originally posted by codepirate
    I have query that returns results like the following:

    request_id field_id field_value
    12345 2 abc
    12345 3 asdf
    12345 11 10
    12346 2 def
    12346 3 asdf
    12346 11 20

    and so on.
    I would like to display the results like this:

    request_id field_2 field_3 field_11
    12345 abc asdf 10
    12346 def asdf 20

    I tried the floowing "pivot" command in SQL 2005:

    select request_id, field_id, field_value
    from some_table
    pivot (
    field_value for field_id in (2, 3, 11)
    )

    but I keep getting this error:

    Error in FROM clause: near 'FOR'.
    Unable to parse query text.

    Does anyone have any idea what I am doing wrong?
    Thanks in advance.
    Check the full syntax here

    -- CK

    Comment

    Working...