我有一个产品表,有产品id和100多个属性.乘积_id是文本,而属性列是整数,即如果属性存在,则为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 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 一个帐号coalesce(Attr1,0)...关于结果.但是为100多列中的每一列输入coalesce是相当困难的.有没有办法用交叉表来处理这个问题?谢谢

推荐答案

您可以使用coalesce:

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

Postgresql相关问答推荐

如何在PostgreSQL中更改分区的表空间?

单个WAL文件中的操作会影响哪些表和多少行

select语句的Jooq代码生成

PostGresql :正则表达式 Select 其中只有一个正斜杠的行

我可以使用 SQLAlchemy 映射数据类创建 Postgres `GENERATED ALWAYS AS` 列吗?

AGE Graph 实际上存储为 postgreSQL 表,对吧?如何检索该表(不是图表)?

在 Age Viewer 上看不到 node 的第一个属性

EF Core添加迁移目标postgreeSQL返回无法加载类型'Microsoft.EntityFrameworkCore.Storage.IRelationalValueBufferFactoryFactory

pgadmin db 限制服务器属性不起作用

PostgreSQL 返回准确或最接近查询日期的日期

AWS RDS 公开访问

PostgreSQL ,从 2 个表中 Select ,但仅从表 2 中 Select 最新的元素

Postgresql - 在 Big Data 库中使用数组的性能

在 PostgreSQL 中表示Sparse稀疏数据

理解 Postgres 行大小

在 PostgreSQL 中跳过每 n 个结果行

Postgres 数据库文件保存在 ubuntu 中的什么位置?

PostgreSQL:如果不存在则创建表 AS

我应该在 Django DATABASE ENGINE 中使用哪个 Postgres 值?

用于将布尔列排序为 true、null、false 的 SQL