2016-02-26 100 views
0

我有一個表,看起來像這樣重新排列PSQL表

------------------------ 
Letter | Status | Count 
A  | active | 3 
A  | offline| 1 
B  | active | 12 
B  | offline| 3 
C  | fixing | 4 
C  | active | 2 

我怎樣才能使它看起來像這樣

----------------------------------- 
Letter | active | offline | fixing 
A  | 3  | 1  | 0 
B  | 12  | 3  | 0 
C  | 2  | 0  | 4 
+0

http://stackoverflow.com/help/how-to-ask –

+0

Dynamic Pivot網站上的幾個例子已經!這裏是[一個例子](http://stackoverflow.com/questions/28337765/postgresql-9-3-dynamic-pivot-table)和[second](http://stackoverflow.com/questions/28087948/dynamic- pivot-query-using-postgresql-9-3),但目前還不清楚你是否想要查詢,或者如果你真的想改變表結構。 – xQbert

+0

@xQbert這兩個示例都不是真正的「動態」,因爲它們需要硬編碼的結果集結構。 BTW。 – Abelisto

回答

0

使用crosstab()這種情況:

-- DDL and data 
CREATE TABLE old (
    letter TEXT, 
    status TEXT, 
    status_count INTEGER 
); 
INSERT INTO old VALUES 
    ('A','active',3), 
    ('A','offline',1), 
    ('B','active',12), 
    ('B','offline',3), 
    ('C','fixing',4), 
    ('C','active',2); 
-- add crosstab function 
CREATE EXTENSION tablefunc; 

CREATE TABLE new_table AS (
    SELECT * FROM crosstab(
    'SELECT * FROM old ORDER BY 1,2', 
    'SELECT DISTINCT status FROM old ORDER BY 1' 
) AS new_table(letter TEXT,active INTEGER,fixing INTEGER,offline INTEGER) 
); 
-- validate 
SELECT * FROM new_table; 

結果:

letter | active | fixing | offline 
--------+--------+--------+--------- 
A  |  3 |  |  1 
B  |  12 |  |  3 
C  |  2 |  4 |   
(3 rows)