Skip to main content
Clarify title, tag, minor formatting
Source Link
Erwin Brandstetter
  • 182.2k
  • 28
  • 457
  • 620

rotating Rotating a table in PostgreSQLwith multiple value columns

I'm not sure if this can be done with crosstab()crosstab(). I've been using this questions/answer as a reference, but am having difficulty putting together the query. 
My table looks like this, just that I have over 50 distinct values in the week column:

rotating a table in PostgreSQL

I'm not sure if this can be done with crosstab(). I've been using this questions/answer as a reference, but am having difficulty putting together the query. My table looks like this, just that I have over 50 distinct values in the week column:

Rotating a table with multiple value columns

I'm not sure if this can be done with crosstab(). I've been using this questions/answer as a reference, but am having difficulty putting together the query. 
My table looks like this, just that I have over 50 distinct values in the week column:

Source Link
AGS
  • 145
  • 1
  • 6

rotating a table in PostgreSQL

I'm not sure if this can be done with crosstab(). I've been using this questions/answer as a reference, but am having difficulty putting together the query. My table looks like this, just that I have over 50 distinct values in the week column:

+------+----+--------+---------+--------+
| week | id | param1 | param2  | param3 |
+------+----+--------+---------+--------+
|    1 |  1 |     13 |      10 |     12 |
|    1 |  2 |     12 |      11 |     44 |
|    2 |  1 |     34 |      33 |      3 |
|    2 |  2 |      3 |      44 |      3 |
+------+----+--------+---------+--------+

I would like to rotate it such that it looks like this:

+----+----------+-----------+----------+----------+----------+----------+-----+
| id | w1param1 | w1param2  | w1param3 | w2param1 | w2param2 | w2param3 | ... |
+----+----------+-----------+----------+----------+----------+----------+-----+
|  1 |       13 |        10 |       12 |       34 |       33 |        3 | ... |
|  2 |       12 |        11 |       44 |        3 |       44 |        3 | ... |
+----+----------+-----------+----------+----------+----------+----------+-----+

where the week column is used to number the parameter columns, and the rows become columns.