SQL 查询以使用连接将 2 行数据合并为单行
SQL Query to get 2 rows data into single row with join
请帮助实现以下结果 table。我尝试加入 3 tables,但不知何故没有得到所需的结果。
Table一个
ID Type Value1 Value2
1 X 100 200
1 Y 200 300
2 X 100 200
Table B
ID Name
1 P
2 Q
3 R
4 S
来自 table 具有匹配值的 A 的唯一 ID
想要的结果
ID Name x_Value1 x_value2 y_value1 y_value2
1 P 100 200 200 300
2 Q 100 200 0 0
如果您想使用 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;
请帮助实现以下结果 table。我尝试加入 3 tables,但不知何故没有得到所需的结果。
Table一个
ID Type Value1 Value2
1 X 100 200
1 Y 200 300
2 X 100 200
Table B
ID Name
1 P
2 Q
3 R
4 S
来自 table 具有匹配值的 A 的唯一 ID
想要的结果
ID Name x_Value1 x_value2 y_value1 y_value2
1 P 100 200 200 300
2 Q 100 200 0 0
如果您想使用 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;