Home > Back-end >  Condition Based Join in SQL Server
Condition Based Join in SQL Server

Time:10-15

I have three tables

  1. Invoice
  2. Organization
  3. Customer

My query is:

Select 
    I.PCD, I.PtypeCD,    
From 
    Invoice I 
Left Join 
    Customer C ON I.PCD = C.CustomerCD 
Left Join 
    Organization O ON I>PDC = O.Organization  

Condition: if PTypecd = 'I' then data come from the Customer table And if Ptypecd = 'O' then data come from the Organization table into Invoice table

How to this condition be used in Join?

CodePudding user response:

Here's a query that joins two tables conditionally, in your case you need to join the Customer table when the PTypecd of Invoice is 1 so add another condition for joint statement AND I.PTypecd = 1, and it the other join you need to check wither I.PTypecd = 0 and that will let you join the other table Organization

SELECT I.PCD, I.PtypeCD
FROM Invoice I
LEFT JOIN Customer a ON a.CustomerCD = i.PDC AND I.PTypecd = 1
LEFT JOIN Organization b ON b.Organization = i.PDC AND i.PTypecd = 0;
  • Related