首页 > 解决方案 > 如何根据 postgres 中的数据执行交叉表?

问题描述

所以看一个官方的例子

CREATE TABLE ct(id SERIAL, rowid TEXT, attribute TEXT, value TEXT);
INSERT INTO ct(rowid, attribute, value) VALUES('test1','att1','val1');
INSERT INTO ct(rowid, attribute, value) VALUES('test1','att2','val2');
INSERT INTO ct(rowid, attribute, value) VALUES('test1','att3','val3');
INSERT INTO ct(rowid, attribute, value) VALUES('test1','att4','val4');
INSERT INTO ct(rowid, attribute, value) VALUES('test2','att1','val5');
INSERT INTO ct(rowid, attribute, value) VALUES('test2','att2','val6');
INSERT INTO ct(rowid, attribute, value) VALUES('test2','att3','val7');
INSERT INTO ct(rowid, attribute, value) VALUES('test2','att4','val8');

SELECT *
FROM crosstab(
  'select rowid, attribute, value
   from ct
   where attribute = ''att2'' or attribute = ''att3''
   order by 1,2')
AS ct(row_name text, category_1 text, category_2 text, category_3 text);

他们从字面上说明列数。他们生产:

 row_name | category_1 | category_2 | category_3
----------+------------+------------+------------
 test1    | val2       | val3       |
 test2    | val6       | val7       |

如何根据总属性对列进行计数以获取以下内容:

 row_name | att1       | att2       | att3       | attr4
----------+------------+------------+---------------------
 test1    | val1       | val2       | val3       | val4
 test2    | val5       | val6       | val7       | val8

由纯表数据组成,而不是由预定义的常量列数组成?

标签: sqlpostgresqlcrosstab

解决方案


推荐阅读