[英]SQL join one column to many based on condition
I have two tables as follows: 我有两张表如下:
Table A 表A.
Docnumber Line Amount Doctype
1000 1 100 3
1000 2 200 3
1001 1 300 5
Table B 表B.
Docnumber Debit Credit Account
1000 100 0 5410
1000 200 0 5560
1001 0 300 6790
I'm trying to create a select which looks like this: 我正在尝试创建一个看起来像这样的选择:
Docnumber Line Amount Account
1000 1 100 5410
1000 2 200 5560
1001 1 300 6790
So, logically, I'm trying to figure out a way to join A.Amount to B.Debit where A.Doctype = 3 and join A.Amount to B.Credit where A.Doctype = 5 所以,从逻辑上讲 ,我试图找出一种方法将A.Amount加入B.Debit,其中A.Doctype = 3并将A.Amount加入B.Credit,其中A.Doctype = 5
As you can see, I'm a novice but any help would be greatly appreciated 如你所见,我是一个新手,但任何帮助将不胜感激
Assuming SQL Server. 假设SQL Server。 Also assuming that
Docnumber
is intended to play a role in your JOIN
as well, despite not being explicitly stated in the question. 同时假设
Docnumber
也打算在你的JOIN
发挥作用,尽管问题中没有明确说明。
You can use any conditions on the JOIN
that you want: 您可以在
JOIN
上使用所需的任何条件:
SELECT A.Docnumber, A.Line, A.Amount, B.Account
FROM A JOIN B
ON A.Docnumber = B.Docnumber
AND ((A.Doctype = 3 AND A.Amount = B.Debit)
OR (A.Doctype = 5 AND A.Amount = B.Credit))
ORDER BY A.Docnumber, A.Line;
Alternatively, you could put it into the WHERE
clause, which is probably more clear: 或者,您可以将其放入
WHERE
子句中,这可能更清楚:
SELECT A.Docnumber, A.Line, A.Amount, B.Account
FROM A JOIN B ON A.Docnumber = B.Docnumber
WHERE (A.Doctype = 3 AND A.Amount = B.Debit) OR (A.Doctype = 5 AND A.Amount = B.Credit)
ORDER BY A.Docnumber, A.Line
Actually easier than you might think! 实际上比你想象的要容易!
SELECT *
FROM A
INNER JOIN B
ON (A.Doctype = 3 AND B.Debit = A.Amount)
OR (A.Doctype = 5 AND B.Credit= A.Amount)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.