我遇到sql join问题(oracle / ms sql) 我有两张桌子
ID | B_ID
--- | ------
1 | 1
1 | 4
2 | 3
2 | 2
----------
B_ID | B_VA | B_VB
------- | -------- | -------
1 | 1 |一个
2 | 2 | b
3 | 5 | ç
4 | 2 | d
-----------------------
从这两个表中我需要A.ID,B.B_ID,B.B_VA(MAX),B.B_VB(最大B.B_VA)
所以结果表就像
ID | B_ID | B_VA | B_VB
------- | -------- | -------- | -------
1 | 4 | 2 | d
2 | 3 | 5 | Ç
我尝试了一些没有成功的连接。任何人都可以帮我查询以获得我想要的结果。
谢谢
答案 0 :(得分:2)
您描述的逻辑与数据不完全对应。例如,b_va
是数字,但输出中的列是字符串。
也许你想要这个。要汇总a
中的数据以获取最大b_id
值。然后,每个要连接的列将获得相应的b_vb
列。这至少符合你想要的输出:
select a.id, a.b_id, b1.b_vb as b_va, b2.b_vb
from (select id, max(b_id) as b_id
from a
group by id
) a join
b b1
on a.id = b1.b_id join
b b2
on a.b_id = b2.b_id;
编辑:
对于更正后的数据,我认为这就是您想要的:
select a.id, a.b_id, max(b1.b_va) as b_va, b2.b_vb
from (select id, max(b_id) as b_id
from a
group by id
) a join
b b1
on a.id = b1.b_id join
b b2
on a.b_id = b2.b_id
group by a.id, a.b_id, b2.b_vb;
答案 1 :(得分:0)
试试这个
SELECT X.ID, Y.B_ID, X.B_VA, Y.B_VB
FROM (SELECT A.ID, MAX(B_VA) AS B_VA
FROM A INNER JOIN B ON A.B_ID = B.B_ID
GROUP BY A.ID) AS X INNER JOIN
A AS Z ON X.ID = Z.ID INNER JOIN
B AS Y ON Z.B_ID=Y.B_ID AND X.B_VA=Y.B_VA