Search code examples
sqlsql-servert-sqlpivotunpivot

How to use the PIVOT or UNPIVOT T-SQL syntax to achieve this output?


I have the following table in my SQL Server database.

  Mkt    Property    Cat    Description   Values     Date
Germany  JohnS Ltd   SUP    RN             150        JUL 16  
Germany  JohnS Ltd   SUP    RN             100        JUL 16
Germany  JohnS Ltd   DLX    RN              60        JUL 16
Germany  JohnS Ltd   DLX    REV             80        JUL 16
Germany  JohnS Ltd   DLX    REV             75        JUL 16

I need my T-SQL query to convert this table (let's call it TblA) and give me the following output:

Mkt         Date       Property      Cat      RN     REV
Germany     JUL 16     JohnS Ltd     SUP      250      0
Germany     JUL 16     JohnS Ltd     DLX       60    155

I am guessing that I should use either the PIVOT or UNPIVOT syntax to achieve this but I am getting confused with the need to aggregate two values (RN and REV) in a PIVOT query (if that is the right way of doing it!).


Solution

  • You need to use PIVOT

    SELECT  Mkt, Date, Property, Cat, RN, REV
    From yourtable
    Pivot (sum([Values]) for Description in ([RN],[REV])) pv
    

    Considering that number of Descriptions is static else you need to use Dynamic Pivot