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

但我希望书名作为列,作者作为行前

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

在postgres中可以吗?我怎样才能做到这一点?

我尝试了交叉表,但我没有做到这一点。

4

1 回答 1

2

您可以使用带有 CASE 表达式的聚合函数来获得结果,但我会首先使用row_number(),因此您有一个可用于对数据进行分组的值。

如果您使用row_number(),则查询可能是:

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;

请参阅SQL Fiddle with Demo。我添加了,row_number()因此您将为书籍返回每个不同的值。如果排除row_number(),则使用带有 CASE 的聚合将只为每本书返回一个值。

此查询给出结果:

|   BOOK1 |   BOOK2 |   BOOK3 |   BOOK4 |
-----------------------------------------
| author1 | author3 | author5 | author7 |
| author2 | author4 | author6 | author8 |
于 2013-08-21T13:37:56.277 回答