--------------------
|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?我怎么能这样做?
我尝试了交叉表,但我没有这样做。
答案 0 :(得分: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 |