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

Pilih baris ketika nilai kolom berubah di antara tanggal di Oracle?

Anda dapat menggunakan COUNT( DISTINCT code ) OVER ( PARTITION BY id ) fungsi analitik untuk mendapatkan jawaban Anda hanya dengan menggunakan satu pemindaian tabel:

SQL Fiddle

Pengaturan Skema Oracle 11g R2 :

CREATE TABLE table_name ( ID, Code, "DATE" ) AS
SELECT 1, 'A', DATE '2018-02-19' FROM DUAL UNION ALL
SELECT 1, 'B', DATE '2018-02-18' FROM DUAL UNION ALL
SELECT 1, 'B', DATE '2018-02-17' FROM DUAL UNION ALL
SELECT 1, 'B', DATE '2018-02-16' FROM DUAL UNION ALL
SELECT 2, 'A', DATE '2018-02-17' FROM DUAL UNION ALL
SELECT 2, 'B', DATE '2018-02-16' FROM DUAL UNION ALL
SELECT 3, 'A', DATE '2018-02-17' FROM DUAL UNION ALL
SELECT 3, 'A', DATE '2018-02-16' FROM DUAL UNION ALL
SELECT 4, 'D', DATE '2018-02-16' FROM DUAL;

Kueri 1 :

SELECT ID,
       Code,
       "DATE"
FROM   (
  SELECT t.*,
         COUNT( DISTINCT code ) OVER ( PARTITION BY id ) AS num_changes
  FROM   table_name t
  WHERE  "DATE" BETWEEN DATE '2018-02-16'
                    AND DATE '2018-02-19'
)
WHERE num_changes > 1

Hasil :

| ID | CODE |                 DATE |
|----|------|----------------------|
|  1 |    A | 2018-02-19T00:00:00Z |
|  1 |    B | 2018-02-18T00:00:00Z |
|  1 |    B | 2018-02-17T00:00:00Z |
|  1 |    B | 2018-02-16T00:00:00Z |
|  2 |    A | 2018-02-17T00:00:00Z |
|  2 |    B | 2018-02-16T00:00:00Z |

Kueri 2 :

SELECT ID,
       Code,
       "DATE"
FROM   (
  SELECT t.*,
         COUNT( DISTINCT code ) OVER ( PARTITION BY id ) AS num_changes
  FROM   table_name t
  WHERE  "DATE" BETWEEN DATE '2018-02-16'
                    AND DATE '2018-02-18'
)
WHERE num_changes > 1

Hasil :

| ID | CODE |                 DATE |
|----|------|----------------------|
|  2 |    A | 2018-02-17T00:00:00Z |
|  2 |    B | 2018-02-16T00:00:00Z |


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Subquery Rekursif dengan penyortiran

  2. Pilih nilai paling minimum kedua di Oracle

  3. Prosedur Oracle PL/SQL berjalan lebih lambat dari SQL

  4. Cari nilai di semua tabel database

  5. Setel ulang Urutan Oracle untuk memiliki MIN VALUE =1 dan nomor MULAI dari 1