如何使用一个选择查询返回重组表?

时间:2017-05-11 03:55:48

标签: sql postgresql pivot crosstab

例如,我有这张表:

+------+--------+-------+--------+-------+
| name | length | width | status | side  |
+------+--------+-------+--------+-------+
| T1   | 5      | 2     | DONE   | Left  |
+------+--------+-------+--------+-------+
| T1   | 2      | 1     | DONE   | Right |
+------+--------+-------+--------+-------+

但需要一个选择查询才能返回:

 +------+-------------+------------+-------------+--------------+-------------+--------------+
| name | left_length | left_width | left_status | right_length | right_width | right_status |
+------+-------------+------------+-------------+--------------+-------------+--------------+
| T1   | 5           | 2          | DONE        | 2            | 1           | DONE         |
+------+-------------+------------+-------------+--------------+-------------+--------------+

这种操作叫做什么? 我正在使用Postgres。

1 个答案:

答案 0 :(得分:1)

以下是使用条件聚合的一种方法:

select name,
    max(case when side = 'Left' then length end) as left_length,
    max(case when side = 'Left' then width end) as left_width,
    max(case when side = 'Left' then status end) as left_status,
    max(case when side = 'Right' then length end) as right_length,
    max(case when side = 'Right' then width end) as right_width,
    max(case when side = 'Right' then status end) as right_status
from your_table
group by name;