SQL Query通过join将2行数据转换为单行

时间:2017-08-24 11:43:22

标签: sql join pivot crosstab

请帮助实现下面的结果表。我尝试加入3个表,不知何故得不到要求的结果。

表A

ID  Type    Value1  Value2
1   X       100     200
1   Y       200     300
2   X       100     200

表B

ID  Name
1   P
2   Q 
3   R
4   S

表A中具有匹配值的唯一ID

期望的结果

ID  Name    x_Value1    x_value2    y_value1    y_value2
1   P       100         200         200         300
2   Q       100         200         0           0

1 个答案:

答案 0 :(得分:1)

如果您想使用join

执行此操作
select b.id, b.name, ax.value1 as value1_x, ax.value2 as value2_x,
       ay.value1 as value1_y, ay.value2 as value2_y
from b left join
     a ax
     on b.id = ax.id and ax.type = 'X' left join
     a ay
     on b.id = ay.id and ay.type = 'Y'
where ax.id is not null or ay.id is not null;