PostgreSQL将2行连接成1行

时间:2012-01-19 21:49:37

标签: postgresql join

如果有重复请指点我。我不知道用什么关键词来搜索这种情况 我有这张桌子:

name    | read  | sum1  | sum2 
--------+-------+-------+-----
A       | 1     | 2.0   | 1.3
A       | 2     | 0.4   | 4  
B       | 1     | 0.2   | 0.1
B       | 2     | 1.0   | 3.3

我想要的是:

name    | r1_sum1 | r1_sum2  | r2_sum1 | r2_sum2 
--------+---------+----------+---------+--------
A       | 2.0     | 1.3      | 0.4     | 4
B       | 0.2     | 0.1      | 1.0     | 3.3

所以就像行按readname列分组一样。我怎么在psql中这样做?

1 个答案:

答案 0 :(得分:1)

您可以将表格加入到自身:

SELECT t1.name AS name,
       t1.sum1 AS r1_sum1,
       t1.sum2 AS r1_sum2,
       t2.sum1 AS r2_sum1,
       t2.sum2 AS r2_sum2
  FROM insert_table_name_here AS t1
  FULL
 OUTER
  JOIN insert_table_name_here AS t2
    ON t1.name = t2.name
   AND t1.read = 1
   AND t2.read = 2
;