简体   繁体   中英

SQL JOIN Query Based on multiple Conditions

According to my table mapping a Company can have many Contacts . So CompanyId is the foreign key in Contact table.

Contact table has a column ContactType which can be MainContact (value 1), AccountsContact (value 2), EmailContact (value 3) etc.

I am just looking to write a SQL query that will return all distinct companies along with contact info based on the condition of first EmailContact (considering lowest Contact primary key ID ) of that Company , but if no email contacts are present, then the 'Main' Contact's info

Sample rows

  • Company1 Info -> Contact Info (First 'EmailContact' and if NOT found 'MainContact')
  • Company2 Info -> Contact Info (First 'EmailContact' and if NOT found 'MainContact')

EXAMPLE

|CompanyId | CompanyName|
    1          ABC Ltd
    2          XYZ Ltd
    3          CCC Ltd


|ContactId | ContactType | EmailAddress     | CompanyId
     1          1          jay@gmail.com       1
     2          3          jim@gmail.com       1
     3          3          ray@gmail.com       2
     4          3          bill@gmail.com      2
     5          1          sally@gmail.com     3

Query Result Expected

CompanyID | CompanyName | ContactId | ContactType |   EmailAddress  | CompanyId
    1         ABC Ltd        2          3           jim@gmail.com       1                   - This loaded EmailContact over MainContact 
    2         XYZ Ltd        3          3           ray@gmail.com       2                   - This considered to load first EmailContact
    3         CCC Ltd        5          1           sally@gmail.com     3                   - This loaded MainContact as no EmailContacts at all

Perhaps you need apply :

select cm.*, cn.*
from Company cm outer apply
     (select top (1) cn.*
      from Contacts cn
      where cn.CompanyID  = cm.CompanyID 
      order by (case when cn.ContactType = 3 then 0 
                     when cn.ContactType = 1 then 1 
                     else 2
                end)
     ) cn;

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