加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-13 16:16:11 所属栏目:百科 来源:网络整理
导读:我有一个带有product_id和100个属性的产品表. product_id是文本,而属性列是整数,即如果属性存在则为1.运行 Postgresql交叉表时,不匹配的atrributes返回空值.如何用零替换空值. SELECT ct.*INTO ct3FROM crosstab('SELECT account_number,attr_name,sub FROM
我有一个带有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,0) as Attr1,coalesce(Attr2,0) as Attr2,etc

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读