简体   繁体   中英

SQL join one column to many based on condition

I have two tables as follows:

Table A

Docnumber  Line  Amount Doctype

1000        1      100     3
1000        2      200     3
1001        1      300     5

Table 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

As you can see, I'm a novice but any help would be greatly appreciated

Assuming 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.

You can use any conditions on the JOIN that you want:

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:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM