Oracle
 sql >> Teknologi Basis Data >  >> RDS >> Oracle

Menambahkan data yang digabungkan ke hasil kueri

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. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Oracle mendapatkan nilai checksum untuk potongan data yang ditentukan oleh klausa pilih

  2. LEAST() Fungsi di Oracle

  3. Memulai Blogging Untuk HTML5 dan CSS3

  4. Oracle STANDARD_HASH tidak tersedia di PLSQL?

  5. Oracle:salin baris saat memperbarui satu bidang