SQL根据条件将一列连接到多个列

时间:2014-03-21 12:54:50

标签: sql

我有两张表如下:

表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

正如您所看到的,我是一个新手,但任何帮助将不胜感激

2 个答案:

答案 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)