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

问题描述 投票:0回答:2

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

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 是相当困难的。有没有办法使用交叉表来处理这个问题?

postgresql null pivot-table zero
2个回答
56
投票

您可以使用合并:

select account_number,
       coalesce(Attr1, 0) as Attr1,
       coalesce(Attr2, 0) as Attr2,
       etc

0
投票

如果你可以将这些属性放入表格中

attr
-----
Attr1

Attr2

Attr3

...

然后你可以自动生成重复的合并语句,如

SELECT 'coalesce("' || attr || '", 0) "'|| attr ||'",' from table;

节省一些打字时间。

© www.soinside.com 2019 - 2024. All rights reserved.