Help Center/ GaussDB/ Centralized_8.x/ SQL Reference/ SQL Syntax/ S/ SELECT/ Rows to Columns and Columns to Rows
Updated on 2024-06-03 GMT+08:00

Rows to Columns and Columns to Rows

  • Rows to columns
    -- Create a table and insert data into the table.
    gaussdb=# CREATE TABLE test_p1(id INT, math INT, english INT);
    gaussdb=# INSERT INTO test_p1 VALUES (1,84,78), (2,98,82), (3,68,59);
    gaussdb=# SELECT * FROM test_p1;
     id | math | english 
    ----+------+---------
      3 |   68 |      59
      1 |   84 |      78
      2 |   98 |      82
    (3 rows)
    
    -- Convert rows to columns.
    gaussdb=# SELECT * FROM test_p1 UNPIVOT(score FOR class IN(math, english));
     id |  class  | score 
    ----+---------+-------
      3 | MATH    |    68
      3 | ENGLISH |    59
      1 | MATH    |    84
      1 | ENGLISH |    78
      2 | MATH    |    98
      2 | ENGLISH |    82
    (6 rows)
    
    -- Delete.
    gaussdb=# DROP TABLE test_p1;
  • Columns to rows
    -- Create a table and insert data into the table.
    gaussdb=# CREATE TABLE test_p2(id INT, class VARCHAR(20), score INT);
    gaussdb=# INSERT INTO test_p2 VALUES (1,'math',64), (1,'english',78);
    gaussdb=# INSERT INTO test_p2 VALUES (2,'math',98), (2,'english',82);
    gaussdb=# INSERT INTO test_p2 VALUES (3,'math',68), (3,'english',59);
    gaussdb=# SELECT * FROM test_p2;
     id |  class  | score 
    ----+---------+-------
      3 | math    |    68
      3 | english |    59
      1 | math    |    64
      1 | english |    78
      2 | math    |    98
      2 | english |    82
    (6 rows)
    
    -- Convert columns to rows.
    gaussdb=# SELECT * FROM test_p2 PIVOT(MAX(score) FOR class IN('math','english'));
     id | 'math' | 'english' 
    ----+--------+-----------
      3 |     68 |        59
      1 |     64 |        78
      2 |     98 |        82
    (3 rows)
    
    -- Delete.
    gaussdb=# DROP TABLE test_p2;