Welcome to MSSQL Forum!
MSSQL Forum - Discussions about Microsoft SQL Server

You are currently viewing our community forums as a guest user. Sign up or
Having an account grants you additional privileges, such as creating and participating in discussions.

Building queries using pivot - Don't forget the alias

Discussion in 'SQL Server Scripts and Tools' started by Peter Schmitz, Jan 31, 2017.

  1. Peter Schmitz

    Peter Schmitz Administrator Staff Member

    TLDR: When writing queries using the PIVOT function, the alias at the end of the pivot.

    Today, while working with the Pivot function, it took me a short while to figure out why my query was not working.

    My query looked just fine:


    Code (text):
    SELECT
        foo, bar
    FROM
        table1
        PIVOT
        (
            AVG(foo) FOR bar IN ([lorem],[ipsum])
        ) ;
    But SSMS wouldn't have it. It complained there was an incorrect syntax near ";".

    The solution of course was to add the alias for the pivot query, like so:

    Code (text):
    SELECT
        foo, bar
    FROM
        table1
        PIVOT
        (
            AVG(foo) FOR bar IN ([lorem],[ipsum])
        ) AS pivottable

Share This Page