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
  • 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. Commented Aug 21, 2013 at 12:23
  • possible duplicate of PostgreSQL Crosstab Query Commented Aug 21, 2013 at 21:17

1 Answer 1

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 |
Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.