[英]Add multi row result of a query as values to another query
I have a problem to solve, that requires me to select multiple values from two tables. 我有一个要解决的问题,需要我从两个表中选择多个值。 From table BI need the values of 3 rows that reference to a key column from table A.
表BI中需要3行的值,这些值引用表A中的键列。
From what I found online I got the feeling, that this seems to come down to nested or recursive/hierarchial selects. 从我在网上找到的东西我感觉到,这似乎可以归结为嵌套或递归/层次选择。 But I can't figure out how to build the actual query with my different conditions between table A and B...
但是我不知道如何在表A和表B之间的不同条件下构建实际的查询...
Given are tables like that: 给出这样的表:
Table A
ID | Val1 | Val2
----------------
01 | QWER | WERT
02 | ASDF | SDFG
...| ... | ...
Table B
ID | Pos | ... | Val5
---------------------
01 | 001 | ... | X
01 | 002 | ... | Y
01 | 003 | ... | F
02 | 001 | ... | J
02 | 002 | ... | R
...| ... | ... | ...
Column ID is obviously the reference value between A and B. 列ID显然是A和B之间的参考值。
I need to build a query like this: 我需要建立这样的查询:
ID | Val1 | Val2 | Val5 at B.Pos 001 | Val5 at B.Pos 002 | Val5 at B.Pos 003
I wasn't able to create a query as follows due to the multiple conditions between A and B and result in a "right bracket missing" error: 由于A和B之间的多种情况,我无法按以下方式创建查询,并导致“缺少右括号”错误:
select
A.ID,
A.Val1,
A.Val2,
(select B.Val5 from B where B.ID = A.ID and B.Pos = 001),
(select B.Val5 from B where B.ID = A.ID and B.Pos = 002),
(select B.Val5 from B where B.ID = A.ID and B.Pos = 003)
from A
Is there a way to do this? 有没有办法做到这一点? It's a case I never encountered before, so I am lost...
我以前从未遇到过这种情况,所以我迷路了...
Is this what you want? 这是你想要的吗?
select a.id, a.val1, a.val2,
max(case when b.pos = 1 then b.val5 end) as bval1,
max(case when b.pos = 2 then b.val5 end) as bval2,
max(case when b.pos = 3 then b.val5 end) as bval3
from a join
b
on a.id = b.id
group by a.id, a.val1, a.val2;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.