Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql pivot? Crosstab?

Tags:

sql

postgresql

I have a table (which is the result of a query) in postgres that has a set of rows (the result of a complicated summation of data) that looks like the following: (The column names are the names of each day, and the value of each column is a double precision.)

Sun   Mon   Tues   Wed   Thurs   Fri
1.24   1.11   4.51   3.21    2.21    1.01

I need to have the data selected from one row so the results look like the below:

Day   Amount
Sun   1.24
Mon   1.11
Tues  4.51
Wed   3.21
Thurs 2.21
Fri      1.01

I'm having difficulty just getting started, as I really need to change the column names to values and pivot the result. I tried experimenting with crosstab but I'm not entirely sure this is what I need. Any advice or suggestions that could get me going in the right direction would be very much appreciated.

like image 596
Tom Lerma Avatar asked Dec 01 '10 20:12

Tom Lerma


1 Answers

Modifying @Jack Douglas's first answer:

SELECT unnest(array['sun', 'mon', 'tue', 'wed', 'thu', 'fri']) AS day,
       unnest(array[sun, mon, tue, wed, thu, fri]) AS amount
FROM t;

A little less costly according to the 9.0 query planner:

Seq Scan on t (cost=0.00..11.62 rows=360 width=192)

versus

Subquery Scan on z (cost=0.00..12.16 rows=360 width=68) -> Seq Scan on t (cost=0.00..11.26 rows=360 width=192)

like image 61
Stew Avatar answered Sep 19 '22 13:09

Stew