我有两张表如下:
表A
Docnumber Line Amount Doctype
1000 1 100 3
1000 2 200 3
1001 1 300 5
表B
Docnumber Debit Credit Account
1000 100 0 5410
1000 200 0 5560
1001 0 300 6790
我试图创建一个如下所示的选择:
Docnumber Line Amount Account
1000 1 100 5410
1000 2 200 5560
1001 1 300 6790
所以,从逻辑上讲,我试图找出一种方法将 A.Amount加入B.Debit,其中A.Doctype = 3并将A.Amount加入B.Credit,其中A.Doctype = 5
正如您所看到的,我是一个新手,但任何帮助将不胜感激
答案 0 :(得分:1)
假设SQL Server。同时假设Docnumber
也打算在您的JOIN
中发挥作用,尽管问题中没有明确说明。
您可以在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;
或者,您可以将其放入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
答案 1 :(得分:1)
实际上比你想象的要容易!
SELECT *
FROM A
INNER JOIN B
ON (A.Doctype = 3 AND B.Debit = A.Amount)
OR (A.Doctype = 5 AND B.Credit= A.Amount)