Search code examples
sqlpivotsql-server-2012ssmsssms-2012

Pivot table wording - SSMS 2012


I'm trying to pivot the PRODUCT column of a table. Values that have two words have an underscore in between:

EX of some PRODUCT values:

PRODUCT
USSIC_Aviation
Avemco_Aviation
Property
Life

This is my pivot code:

select SIMULATION, [USSIC Aviation], [Avemco Aviation], [Property], [Life]
from CM.CorrelationData
pivot
(
min(Value)
for replace(PRODUCT,'_',' ') in ([USSIC Aviation], [Avemco Aviation], [Property], [Life])
) piv
where Product_Description='UW' 

It doesn't like the replace(PRODUCT,'_',' ') but I don't know how else to get rid of the underscore. Any help will be appreciated!


Solution

  • You cannot perform a replace in the PIVOT area of the query so you will need to perform it in a subquery:

    select SIMULATION, [USSIC Aviation], [Avemco Aviation], [Property], [Life]
    from
    (
      select SIMULATION, replace(PRODUCT,'_',' ') Product, value
      from  CM.CorrelationData
      where Product_Description='UW' 
    ) d
    pivot
    (
      min(Value)
      for PRODUCT in ([USSIC Aviation], [Avemco Aviation], [Property], [Life])
    ) piv