Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace null values in sql pivot

I have the following query :

SELECT *
FROM Table1
PIVOT
(
  SUM(Value)
  FOR [Period] IN ([06/1/2007],[07/1/2007])
)
AS p

Some of the rows returned are null but i want to replace them with 0.

I've tried SUM(ISNULL(Value,0)) as Val but it's not working. ( it's saying incorrect syntax)

like image 475
Iulian Avatar asked Jul 21 '10 07:07

Iulian


People also ask

How do you replace null values with zero output in pivot?

You can use isnull or coalesce to substitute a 0 for null values.

How do you replace null values to zero in dynamic pivot in SQL Server?

You need to incorporate ISNULL() into each item in the @sourcecolumn list in the SELECT clause. The reason it threw an error is because your entire list of columns was wrapped in one statement: ISNULL(col1,col2,col3...,0) you need ISNULL(col1,0),ISNULL(col2,0)...

Is null in pivot SQL?

The SQL value null represents the absence of data, so when you pivot and a cell as no data a null will perforce be generated as the cell value.


1 Answers

Ohh, I was using ISNULL in the wrong place.

the query should look like this:

SELECT ID,ISNULL([06/1/2007],0), ISNULL([07/1/2007],0)
FROM Table1
PIVOT
(
  SUM(Value)
  FOR [Period] IN ([06/1/2007],[07/1/2007])
)
AS p
like image 162
Iulian Avatar answered Sep 21 '22 04:09

Iulian