sql >> Database >  >> RDS >> Oracle

Samengevoegde gegevens toevoegen aan een queryresultaat

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 |


  1. MySQL - Rangschikking per maand over meerdere maanden

  2. Kun je if-then-else-logica in SQL hebben?

  3. Fix "ERROR 1250 (42000):Tabel '...' van een van de SELECT's kan niet worden gebruikt in de ORDER-clausule" in MariaDB

  4. Rails:FATAL - Peer-authenticatie mislukt voor gebruiker (PG::Error)