重新排列PSQL表

时间:2016-02-26 21:29:51

标签: sql postgresql pivot crosstab

我有一张看起来像这样的表

------------------------
 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

1 个答案:

答案 0 :(得分: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)