WITH indexed_users AS ( SELECT u.*, ROW_NUMBER() OVER ( PARTITION BY Company_ID ORDER BY Name ) AS idx FROM Users u),indexed_contractors AS ( SELECT c.*, ROW_NUMBER() OVER ( PARTITION BY Company_ID ORDER BY Name ) AS idx FROM Contractors c),indexed_users_and_contractors AS ( SELECT COALESCE( u.Company_ID, c.Company_ID ) AS Company_ID, u.Name AS UserName, c.Name AS ContractorName, COALESCE( u.idx, c.idx ) AS idx FROM indexed_users u FULL OUTER JOIN indexed_contractors c ON ( u.Company_id =c.Company_ID AND u.idx =c.idx ) ORDER BY 4)SELECT c.Name, i.UserName, i.ContractorNameFROM Companies c LEFT OUTER JOIN indexed_users_and_contractors i ON ( c.Company_ID =i.Company_ID )ORDER BY c.Name, i.idx
SQL Fiddle
:
<предварителен код>| ИМЕ | ПОТРЕБИТЕЛСКО ИМЕ | ИМЕ НА ИЗПЪЛНИТЕЛЯ ||----------|----------|----------------|| Компания1 | Потребител1 | Изпълнител1 || Компания1 | Потребител2 | Изпълнител2 || Компания2 | Потребител3 | Изпълнител1 || Компания2 | Потребител4 | (нула) || Компания3 | Потребител5 | Изпълнител2 || Компания3 | (нула) | Изпълнител3 |