如何在postgresql交叉表中用零替换空值

我有一个带有product_id和100个属性的产品表. product_id是文本,而属性列是整数,即如果属性存在则为1.运行Postgresql交叉表时,不匹配的atrributes返回空值.如何用零替换空值.

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,
...
)

替换此结果:

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

以下是:

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

解决方法是在结果上执行select account_number,coalesce(Attr1,0)….但是为100列中的每一列键入coalesce是相当不合理的.有没有办法使用交叉表处理这个?谢谢

你可以使用coalesce:

select account_number,
       coalesce(Attr1, 0) as Attr1,
       coalesce(Attr2, 0) as Attr2,
       etc
翻译自:https://stackoverflow.com/questions/6355177/how-to-replace-nulls-with-zeros-in-postgresql-crosstabs

转载注明原文:如何在postgresql交叉表中用零替换空值