如何在postgres中执行基于数据的交叉表?

i34xakig  于 2021-07-26  发布在  Java
关注(0)|答案(0)|浏览(135)

看看一个官方的例子:

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       |

如何基于total属性对列进行计数以获得以下行:

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

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

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题