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

SQL Oracle - Menggabungkan baris berurutan dengan filter

Empat tahun telah berlalu sejak pertanyaan ini diajukan. Tetapi Oracle menambahkan MATCH_RECOGNIZE klausa ke Oracle 12c, dan ini membuat solusinya lebih sederhana.

SELECT
  foo_id, high_speed, speed,
  NVL(DateFromZ, DateFrom) DateFrom,
  NVL(DateToZ, DateTo) DateTo
FROM test
MATCH_RECOGNIZE (
  ORDER BY RecordId
  MEASURES
    FIRST(zeros.DateFrom) AS DateFromZ,
    FINAL LAST(zeros.DateTo) AS DateToZ,
    COUNT(*) AS cnt
  ALL ROWS PER MATCH WITH UNMATCHED ROWS
  PATTERN (zeros+)
  DEFINE
    zeros AS zeros.speed = 0
)
WHERE speed > 0 OR cnt = 1
ORDER BY RecordId;

Keluaran:

+--------+------------+-------+------------+------------+
| FOO_ID | HIGH_SPEED | SPEED |  DATEFROM  |   DATETO   |
+--------+------------+-------+------------+------------+
|     12 |         60 |    10 | 09/11/2011 | 10/11/2011 |
|     13 |         20 |    20 | 11/11/2011 | 11/11/2011 |
|     12 |          0 |     0 | 13/11/2011 | 14/11/2011 |
|     12 |         70 |    50 | 15/11/2011 | 26/11/2011 |
|     12 |         40 |    40 | 09/11/2011 | 09/11/2011 |
|     13 |         25 |    20 | 09/11/2011 | 09/11/2011 |
|     12 |          0 |     0 | 15/11/2011 | 19/11/2011 |
|     12 |         20 |    10 | 12/11/2011 | 12/11/2011 |
+--------+------------+-------+------------+------------+

Demo di db<>biola .




  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Cara memperbarui kolom JSON di Oracle 12.1

  2. PROSEDUR ORACLe - AUTHID hanya diizinkan di tingkat skema

  3. Oracle SQL:Cara membaca dan menambah bidang

  4. Bisakah Oracle SQL*Loader memproses XML?

  5. SQL Pengenal Tidak Valid