2017-05-11 1 views
0

Par exemple, j'ai ce tableau:Comment utiliser une requête de sélection pour renvoyer une table restructurée?

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

Mais besoin d'une requête de sélection pour revenir:

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

Quel est ce genre d'opération appelée? J'utilise Postgres.

+2

Vous pouvez utiliser la solution d'agrégation conditionnelle prévue dans la réponse, ou vous pouvez installer le module tablefunc et utiliser la fonction de tableau croisé, comme décrit ici: http://stackoverflow.com/questions/3002499/postgresql-crosstab-query – cha

+0

Merci pour la terminologie. Je n'avais aucune idée de quoi chercher. Je vois que j'ai beaucoup à lire maintenant! –

Répondre

1

Voici une façon de le faire en utilisant l'agrégation conditionnelle:

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;