在 postgresql 中旋转 table
pivoting table in postgresql
我有什么
customerid status
Ax 1
Bx 3
Cx 5
Dx 4
Ex 2
我希望在 table 上方旋转。
我需要什么
customerid status_1 status_2 status_3 status_4 status_5
Ax 1 0 0 0 0
Bx 0 0 1 0 0
Cx 0 0 0 0 1
Dx 0 0 0 1 0
Ex 0 1 0 0 0
select customerid,
case when status = 1 then 1 else 0 end as status_1,
case when status = 2 then 1 else 0 end as status_2,
case when status = 3 then 1 else 0 end as status_3,
case when status = 4 then 1 else 0 end as status_4,
case when status = 5 then 1 else 0 end as status_5
from your_table
order by customerid;
在 Postgres 中使用 tablefunc
module
postgres=# create extension tablefunc ;
CREATE EXTENSION
postgres=# create table your_table (customerid char(2),status int);
insert into your_table values('Ax',1),('Bx',3),('Cx',5),('Dx',4),('Ex',2);
CREATE TABLE
INSERT 0 5
postgres=# SELECT * FROM crosstab(
$$select customerid, status,
count(status) AS "# of status"
from your_table group by customerid, status
order by customerid,status$$ ,
$$select distinct status from your_table
order by status$$)
AS ("customerid" text,
"status_1" text, "status_2" text, "status_3" text,
"status_4" text, "status_5" text);
customerid | status_1 | status_2 | status_3 | status_4 | status_5
------------+----------+----------+----------+----------+----------
Ax | 1 | | | |
Bx | | | 1 | |
Cx | | | | | 1
Dx | | | | 1 |
Ex | | 1 | | |
(5 rows)
postgres=#
我有什么
customerid status
Ax 1
Bx 3
Cx 5
Dx 4
Ex 2
我希望在 table 上方旋转。
我需要什么
customerid status_1 status_2 status_3 status_4 status_5
Ax 1 0 0 0 0
Bx 0 0 1 0 0
Cx 0 0 0 0 1
Dx 0 0 0 1 0
Ex 0 1 0 0 0
select customerid,
case when status = 1 then 1 else 0 end as status_1,
case when status = 2 then 1 else 0 end as status_2,
case when status = 3 then 1 else 0 end as status_3,
case when status = 4 then 1 else 0 end as status_4,
case when status = 5 then 1 else 0 end as status_5
from your_table
order by customerid;
在 Postgres 中使用 tablefunc
module
postgres=# create extension tablefunc ;
CREATE EXTENSION
postgres=# create table your_table (customerid char(2),status int);
insert into your_table values('Ax',1),('Bx',3),('Cx',5),('Dx',4),('Ex',2);
CREATE TABLE
INSERT 0 5
postgres=# SELECT * FROM crosstab(
$$select customerid, status,
count(status) AS "# of status"
from your_table group by customerid, status
order by customerid,status$$ ,
$$select distinct status from your_table
order by status$$)
AS ("customerid" text,
"status_1" text, "status_2" text, "status_3" text,
"status_4" text, "status_5" text);
customerid | status_1 | status_2 | status_3 | status_4 | status_5
------------+----------+----------+----------+----------+----------
Ax | 1 | | | |
Bx | | | 1 | |
Cx | | | | | 1
Dx | | | | 1 |
Ex | | 1 | | |
(5 rows)
postgres=#