sql - 如何根据 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
由纯表数据组成,而不是由预定义的常量列数组成?
解决方案
推荐阅读
- flutter - Dart,Flutter : const 修饰符的含义,Colors.yellow [200] 不是常量吗?
- php - 如何验证 PayPal 订阅
- go - 如何在golang中的JSON类型中插入空值
- ffmpeg - 视频片段的两个ffmpeg命令的比较
- python - 散点图:获取 ValueError(x 和 y 必须相同大小)
- python - 在数据框中查找具有特定字符串值的连续行?
- python - Python Module CSV 在 CSV 文件的 writen 行之间添加一个空行
- python - 在 python 中创建带有正则表达式错误的 if/elif 语句
- javascript - 我得到了 base64 [目标文件],如何将其转换为正确的 base64 文件?
- reactjs - 无法在渲染中调用函数