27

product_idと100以上の属性を持つproductテーブルがあります。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以上の列のそれぞれに合体を入力するのはかなりやりがいがありません。クロス集計を使用してこれを処理する方法はありますか?ありがとう

4

2 に答える 2

45

合体を使用できます:

select account_number,
       coalesce(Attr1, 0) as Attr1,
       coalesce(Attr2, 0) as Attr2,
       etc
于 2011-06-15T10:52:22.000 に答える
0

それらの属性を次のようなテーブルに配置できる場合

attr
-----
Attr1

Attr2

Attr3

...

次に、次のような繰り返しの合体ステートメントを自動的に生成できます。

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

タイピングを節約します。

于 2016-05-31T17:23:32.807 に答える