I tried to convert the (null) values with 0 (zeros) output in PIVOT function but have no sucess.
Below is the table and the syntax i've tried"
SELECT
CLASS,
[AZ],
[CA],
[TX]
FROM #TEMP
PIVOT (SUM(DATA)
FOR STATE IN ([AZ], [CA], [TX])) AS PVT
ORDER BY CLASS
CLASS AZ CA TX
RICE 10 4 (null)
COIN 30 3 2
VEGIE (null) (null) 9
I tried to use the ISNULL
but did not work.
PIVOT SUM(ISNULL(DATA,0)) AS QTY
Could someone please look into its syntax error? Thanks a lot!
You have to account for all values in the pivot set. you can accomplish this using a cartesian product.
To modify the results under pivot, you can put the columns in the selected fields and then modify them accordingly. May be you can use DECODE for the columns you have built using pivot function.
Sometimes it's better to think like a parser, like T-SQL parser. While executing the statement, parser does not have any value in Pivot section and you can't have any check expression in that section. By the way, you can simply use this:
If you have a situation where you are using dynamic columns in your pivot statement you could use the following:
You cannot place the
IsNull()
until after the data is selected so you will place theIsNull()
around the final value in theSELECT
: