在 PostgreSQL 中将行转换为列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41652740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert rows to column in PostgreSQL
提问by nagi
I want to convert rows to column in PostgreSQL.I want all variables against their respective id.but its not working.
我想在 PostgreSQL 中将行转换为列。我希望所有变量都针对它们各自的 id。但它不起作用。
Expected Output:
预期输出:
myvar desc fname lname sdate edate id
title1 desc1 cina jhon 1483920000000 1484524800000 14
title2 desc2 jhon lname2 1483920000000 1483910000000 16
title3 desc3 diesel zier 1483920000000 1484524800000 17
SELECT * FROM crosstab(
'SELECT name, value, id FROM test ORDER BY id') AS (
"myVar" text, "desc" text, "fname" text, "lname" text,"sdate" text,"edate" text, "value" text ,"containerid" bigint);
Error: ERROR: invalid return type SQL state: 42601 Detail: SQL rowid datatype does not match return rowid datatype.
错误:错误:无效的返回类型 SQL 状态:42601 详细信息:SQL rowid 数据类型与返回 rowid 数据类型不匹配。
回答by McNets
Maybe this can helps.
也许这会有所帮助。
ORDER BY 1,2
is required here.
ORDER BY 1,2
这里需要。
select *
from crosstab (
'select id, name, value
from tt1
order by 1,2')
AS (row_name int, col1 text, col2 text, col3 text, col4 text);
+----------+-------+--------+--------+--------+
| row_name | col1 | col2 | col3 | col4 |
+----------+-------+--------+--------+--------+
| 14 | desc1 | chen | john | title1 |
+----------+-------+--------+--------+--------+
| 15 | desc2 | fname2 | lname2 | title2 |
+----------+-------+--------+--------+--------+
| 16 | desc4 | deiser | ziel | title3 |
+----------+-------+--------+--------+--------+
In fact, columns should be named as: col1, col2, col3, col4, ...
实际上,列应该命名为:col1、col2、col3、col4、...
Check it here: http://rextester.com/MFWAW58518
在这里查看:http: //rextester.com/MFWAW58518