在同一个表PostgreSql上连接多个选择查询

时间:2018-04-04 20:25:22

标签: sql postgresql join

下面是我得到的示例表结构,

C1  C2  C3 C4
A   D   G  X
B   E   H  X
C   F   I  X

select C2 as 1_C2, C3 as 1_C3 from table1 where C1 = A and C4=X
select C2 as 2_C2, C3 as 2_C3 from table1 where C1 = B and C4=X
select C2 as 3_C2, C3 as 3_C3 from table1 where C1 = C and C4=X

以上是我所得到的三个选择陈述。现在我需要连接所有三个select语句,并只输出一行作为输出,如

1_C2 2_C2 3_C2 1_C3 2_C3 3_C3    
   D    E    F    G    H    I

看到多个其他帖子,但不符合此要求。任何帮助都非常感谢。

1 个答案:

答案 0 :(得分:2)

您可以使用CASE表达式,结合MAX():

select MAX(CASE WHEN C1 = 'A' THEN C2 END) as 1_C2,
       MAX(CASE WHEN C1 = 'B' THEN C2 END) as 2_C2,
       MAX(CASE WHEN C1 = 'C' THEN C2 END) as 3_C2,
       MAX(CASE WHEN C1 = 'A' THEN C3 END) as 1_C3,
       MAX(CASE WHEN C1 = 'B' THEN C3 END) as 2_C3,
       MAX(CASE WHEN C1 = 'C' THEN C3 END) as 3_C3
  from table1
 where C1 in ('A', 'B', 'C')
   and C4 = 'X';