how to use case inside pivot

  • Hi ,

    I am wondering if case is allowed in pivot.

    For example,

    instead of directly doing pivot( sum(Amt1) for Col1 in (a,b,c))

    i want to do it this way...

    pivot ( case when @Var = 'TBT' then sum(Amt1)

    when @Var = 'BBT' then sum(Amt2) end

    for Col1 in (a,b,c))

    Is this Possible?

    Can you suggest me a way to acheive this?

    Thanks,

  • Add the CASE to the query before the PIVOT (the one that defines the data that is pivoted):

    CASE WHEN @Var = 'TBT' THEN Amt1

    WHEN @Var = 'BBT' THEN Amt2 ELSE 0 END AS PivotAmt

    Then, pivot on the calculated value:

    PIVOT SUM(PivotAmt) FOR Col1 IN (a,b,c)

    -Eddie

    Eddie Wuerch
    MCM: SQL

Viewing 2 posts - 1 through 1 (of 1 total)

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