如何在postgresql交叉表中用零替换空值
我有一个产品表,其中包含产品id和100多个属性。产品标识为文本,而属性列为整数,即如果属性存在,则为1。在运行Postgresql交叉表时,不匹配的AtrAttribute返回空值。如何用零替换空值如何在postgresql交叉表中用零替换空值,postgresql,null,zero,crosstab,Postgresql,Null,Zero,Crosstab,我有一个产品表,其中包含产品id和100多个属性。产品标识为文本,而属性列为整数,即如果属性存在,则为1。在运行Postgresql交叉表时,不匹配的AtrAttribute返回空值。如何用零替换空值 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 OR
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
一个解决方法是选择一个帐号,coalesce(Attr1,0)。。。关于结果。但是为100多列中的每一列键入coalesce是相当困难的。有没有办法用交叉表来处理这个问题?谢谢您可以使用coalesce:
select account_number,
coalesce(Attr1, 0) as Attr1,
coalesce(Attr2, 0) as Attr2,
etc
如果你能把这些属性放到一个表中
attr
-----
Attr1
Attr2
Attr3
...
然后可以自动生成重复的coalesce语句,如
SELECT 'coalesce("' || attr || '", 0) "'|| attr ||'",' from table;
节省一些打字时间