如何在PostgreSQL交叉表中用零代替空值

问题描述

|| 我有一个带有product_id和100多个属性的产品表。 product_id是文本,而属性列是整数,即1(如果该属性存在)。当运行Postgresql交叉表时,不匹配的属性将返回空值。如何用零代替空值。
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
解决方法是对结果进行选择account_number,coalesce(Attr1,0)...。但是,要为100多个列中的每一个键入合并都是相当困难的。有没有办法使用交叉表来解决这个问题?谢谢     

解决方法

        您可以使用合并:
select account_number,coalesce(Attr1,0) as Attr1,coalesce(Attr2,0) as Attr2,etc
    ,        如果您可以将这些Attrs放入表格 属性 Attr1 Attr2 Attr3 ... 那么您可以自动生成重复的合并语句,例如
SELECT \'coalesce(\"\' || attr || \'\",0) \"\'|| attr ||\'\",\' from table;
保存一些输入内容。     

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...