pivot table invalid column

  • what i am doing wrong here.

    SELECT BUSINESS_NAME,CONTRACT_CATEGORY,[RX],[PRODUCT]

    FROM (

    SELECT

    BUSINESS_NAME ,

    CONTRACT_CATEGORY ,

    VALUE,

    NAME

    FROM PRODUCT_CAT)UP

    pivot (SUM(VALUE) FOR NAME IN (['RX'],['PRODUCT']))AS S

    i am getting invalid column name rx and product.

  • Quick suggestion, add the column names to the CTE

    😎

    SELECT BUSINESS_NAME,CONTRACT_CATEGORY,[RX],[PRODUCT]

    FROM (

    SELECT

    BUSINESS_NAME ,

    CONTRACT_CATEGORY ,

    VALUE,

    NAME

    FROM PRODUCT_CAT)UP (BUSINESS_NAME,CONTRACT_CATEGORY,[RX],[PRODUCT])

    pivot (SUM(VALUE) FOR NAME IN (['RX'],['PRODUCT']))AS S

  • Just remove the single quotes.

    Luis C.
    General Disclaimer:
    Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?

    How to post data/code on a forum to get the best help: Option 1 / Option 2
  • You could also try a cross tabs approach.

    SELECT BUSINESS_NAME,

    CONTRACT_CATEGORY,

    SUM( CASE WHEN NAME = 'RX' THEN VALUE ELSE 0 END) AS RX,

    SUM( CASE WHEN NAME = 'PRODUCT' THEN VALUE ELSE 0 END) AS [PRODUCT]

    FROM (

    SELECT

    BUSINESS_NAME ,

    CONTRACT_CATEGORY ,

    SUM(VALUE) AS VALUE,

    NAME

    FROM PRODUCT_CAT

    GROUP BY BUSINESS_NAME ,

    CONTRACT_CATEGORY ,

    NAME)UP

    GROUP BY BUSINESS_NAME ,

    CONTRACT_CATEGORY;

    Luis C.
    General Disclaimer:
    Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?

    How to post data/code on a forum to get the best help: Option 1 / Option 2

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

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