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.ContractorName
FROM 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
:
| NAME | USERNAME | CONTRACTORNAME |
|----------|----------|----------------|
| Company1 | User1 | Contractor1 |
| Company1 | User2 | Contractor2 |
| Company2 | User3 | Contractor1 |
| Company2 | User4 | (null) |
| Company3 | User5 | Contractor2 |
| Company3 | (null) | Contractor3 |