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

cara membagi kolom dalam hasil kueri di database oracle

Gunakan PIVOT dan ROW_NUMBER fungsi analitik:

SQL Fiddle

Pengaturan Skema Oracle 11g R2 :

CREATE TABLE your_query_result (sal, cat, id, shop ) AS
SELECT 1900,   '34R5',   10,   'dense' FROM DUAL UNION ALL
SELECT 1900,   '34r5',   10,   'SVM' FROM DUAL UNION ALL
SELECT 1900,   '34r5',   10,   'bpo' FROM DUAL UNION ALL
SELECT 2345,   '3ER4',   11,   'kpo' FROM DUAL UNION ALL
SELECT 2345,   '3ER4',   11,   'infra' FROM DUAL UNION ALL
SELECT 12345,  '34F4',   12,   'const' FROM DUAL;

Kueri 1 :

SELECT sal,
       cat,
       id,
       "1_SHOP" AS shop_1,
       "2_SHOP" AS shop_2,
       "3_SHOP" AS shop_3
FROM   (
  SELECT r.*,
         ROW_NUMBER() OVER (
           PARTITION BY sal, cat, id
           ORDER BY shop
         ) AS rn
  FROM   (
    SELECT * FROM your_query_result
  ) r
)
PIVOT (
  MAX( shop ) AS shop
  FOR rn IN ( 1, 2, 3 )
)

Hasil :

|   SAL |  CAT | ID | SHOP_1 | SHOP_2 | SHOP_3 |
|-------|------|----|--------|--------|--------|
|  1900 | 34R5 | 10 |  dense | (null) | (null) |
|  1900 | 34r5 | 10 |    SVM |    bpo | (null) |
|  2345 | 3ER4 | 11 |  infra |    kpo | (null) |
| 12345 | 34F4 | 12 |  const | (null) | (null) |

Jika Anda ingin baris pertama dan kedua pada baris yang sama maka cukup ubah CAT kolom harus dalam huruf kecil sebelum membuat ROW_NUMBER dan PIVOT ing.




  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Menambahkan nama Skema ke entitas di data Spring?

  2. Daftar Dipisahkan koma

  3. OracleCommandBuilder.DeriveParameters() melempar OracleException:ORA-06564:objek tidak ada ORA-06512:di SYS.DBMS_UTILITY

  4. Apakah ada Oracle yang setara dengan OUTPUT INSERTED.* SQL Server?

  5. MySQL setara dengan Oracle's SEQUENCE.NEXTVAL