[英]Postgres pivot table with additional columns
I need to realize a pivot table in Postgres, but I have no idea how to do it.我需要在 Postgres 中实现一个 pivot 表,但我不知道该怎么做。 The function to use should be the crosstab()
, but I'm not sure I know how to use it properly.使用的 function 应该是crosstab()
,但我不确定我是否知道如何正确使用它。
Given a table like this:给定这样的表:
column a | column b | column c | value 1 | value 2
0 |
1 |
2 |
3 |
4 |
I have to get something like this:我必须得到这样的东西:
column c | Column b | 0 | 1 | 2 | 3 | 4
| |value 1|value 1|value 1|value 1|value 1|
| |
So I need to get the row 0, ... , 4 as columns, and value 1
as values.所以我需要将第 0 行、...、第 4 行作为列,将value 1
作为值。 crosstab()
function wants 3 columns, nut I need column c
and column b
both to appear. crosstab()
function 想要 3 列,螺母我需要column c
和column b
都出现。
"column c"
and "column b"
are a so-called "extra" columns. "column c"
和"column b"
是所谓的“extra”列。 Put them after the row name and before the category:将它们放在行名之后和类别之前:
SELECT * FROM crosstab(
'SELECT "column a", "column c", "column b"
,"value 2", "value 1"
FROM tbl
ORDER BY 1'
, 'VALUES (0), (1), (2), (3), (4)'
) AS ct (
"column a" text
, "column c" text
, "column b" text
, "0" int
, "1" int
, "2" int
, "3" int
, "4" int);
To address your comment:要解决您的评论:
These are nested numeric literals, which need no quoting:这些是嵌套的数字文字,不需要引用:
, 'VALUES (0), (1), (2), (3), (4)'
String literals require quoting (I use to dollar-quoting for the outer quote now):字符串文字需要引用(我现在用美元引用外部引号):
, $$VALUES ('V0'), ('V1'), ('V2'), ('V3'), ('V4')$$
Or:或者:
, $$SELECT unnest('{V0,V1,V2,V3,V4}'::text[])$$
See:看:
About crosstab()
:关于crosstab()
:
... with extra columns: ...带有额外的列:
And consider sane column names.并考虑合理的列名。 (Assuming given names are just symbolic.) (假设给定的名称只是象征性的。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.