Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace nulls with zeros in postgresql crosstabs

I've a product table with product_id and 100+ attributes. The product_id is text whereas the attribute columns are integer, i.e. 1 if the attribute exists. When the Postgresql crosstab is run, non-matching atrributes return null values. How do I replace nulls with zeros instead.

SELECT ct.* INTO ct3 FROM crosstab( 'SELECT account_number, attr_name, sub FROM products ORDER BY 1,2', 'SELECT DISTINCT attr_name FROM attr_names ORDER BY 1') AS ct( account_number text, Attr1 integer, Attr2 integer, Attr3 integer, Attr4 integer, ... ) 

Replace this result:

account_number  Attr1   Attr2   Attr3   Attr4 1.00000001  1   null    null    null 1.00000002      null    null    1   null 1.00000003  null    null    1   null 1.00000004  1   null    null    null 1.00000005  1   null    null    null 1.00000006  null    null    null    1 1.00000007  1   null    null    null 

with this below:

account_number  Attr1   Attr2   Attr3   Attr4 1.00000001  1   0   0   0 1.00000002  0   0   1   0 1.00000003  0   0   1   0 1.00000004  1   0   0   0 1.00000005  1   0   0   0 1.00000006  0   0   0   1 1.00000007  1   0   0   0 

A workaround would be to do a select account_number, coalesce(Attr1,0)... on the result. But typing out coalesce for each of the 100+ columns is rather unyieldly. Is there a way to handle this using crosstab? Thanks

like image 343
Mike Avatar asked Jun 15 '11 08:06

Mike


People also ask

How do I replace NULL with 0?

Use IFNULL or COALESCE() function in order to convert MySQL NULL to 0. Insert some records in the table using insert command. Display all records from the table using select statement.

How do you replace all NULL values?

The ISNULL Function is a built-in function to replace nulls with specified replacement values. To use this function, all you need to do is pass the column name in the first parameter and in the second parameter pass the value with which you want to replace the null value.

How do you handle NULL values in PostgreSQL?

nullif also used with the coalesce function to handle the null values. PostgreSQL nullif function returns a null value if provided expressions are equal. If two expressions provided are equal, then it provides a null value; as a result, otherwise, it will return the first expression as a result.

What is NVL equivalent in PostgreSQL?

PostgreSQL does not support nvl functions, but it supports coalesce functions. The usage is the same with that in Oracle. You can utilize coalesce to convert nvl and coalesce functions of Oracle. The arguments have to be of the same type, or can be automatically converted to the same type.


1 Answers

You can use coalesce:

select account_number,        coalesce(Attr1, 0) as Attr1,        coalesce(Attr2, 0) as Attr2,        etc 
like image 84
Denis de Bernardy Avatar answered Oct 14 '22 03:10

Denis de Bernardy