Mik*_*ike 14 postgresql null crosstab zero
我有一个带有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,
...
)
Run Code Online (Sandbox Code Playgroud)
替换此结果:
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
Run Code Online (Sandbox Code Playgroud)
以下是:
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
Run Code Online (Sandbox Code Playgroud)
解决方法是在结果上执行select account_number,coalesce(Attr1,0).... 但是,为100多列中的每一列键入coalesce是相当不可思议的.有没有办法使用交叉表处理这个?谢谢
Den*_*rdy 23
你可以使用coalesce:
select account_number,
coalesce(Attr1, 0) as Attr1,
coalesce(Attr2, 0) as Attr2,
etc
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22400 次 |
| 最近记录: |