0
--------------------
|bookname |author   |
--------------------
|book1    |author1  |
|book1    |author2  |
|book2    |author3  |
|book2    |author4  |
|book3    |author5  |
|book3    |author6  |
|book4    |author7  |
|book4    |author8  |
---------------------

but I want the booknames as columns and authors as its rows ex

----------------------------------
|book1  |book2   |book3  |book4  |
----------------------------------
|author1|author3 |author5|author7|
|author2|author4 |author6|author8|
----------------------------------

is it possible in postgres? How can I do this?

I tried crosstab but I failed to do this.

  • 2
    "*I tried crosstab but I failed to do this*" - crosstab is the way to go. Show us what you tried and the exact error message. –  Aug 21 '13 at 12:23
  • possible duplicate of [PostgreSQL Crosstab Query](http://stackoverflow.com/questions/3002499/postgresql-crosstab-query) – swasheck Aug 21 '13 at 21:17

1 Answers1

2

You can get the result using an aggregate function with a CASE expression but I would first use row_number() so you have a value that can be used to group the data.

If you use row_number() then the query could be:

select 
  max(case when bookname = 'book1' then author end) book1,
  max(case when bookname = 'book2' then author end) book2,
  max(case when bookname = 'book3' then author end) book3,
  max(case when bookname = 'book4' then author end) book4
from
(
  select bookname, author,
    row_number() over(partition by bookname
                      order by author) seq
  from yourtable
) d
group by seq;

See SQL Fiddle with Demo. I added the row_number() so you will return each distinct value for the books. If you exclude the row_number(), then using an aggregate with a CASE will return only one value for each book.

This query gives the result:

|   BOOK1 |   BOOK2 |   BOOK3 |   BOOK4 |
-----------------------------------------
| author1 | author3 | author5 | author7 |
| author2 | author4 | author6 | author8 |
Taryn
  • 242,637
  • 56
  • 362
  • 405
  • Thanks it works but if book numbers increases then I should have to increase this statements. **max(case when bookname = 'book4' then author end) book4** is there any way to create columns dynamically?? – user2703248 Aug 22 '13 at 06:47