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

menambah nomor baris ketika nilai bidang berubah di Oracle

Anda dapat menggabungkan fungsi analitik SUM (digunakan sebagai total berjalan) dan LAG :

SQL> WITH data AS (
  2            SELECT 'person1' person, 'day1' day, 'Y' flag FROM dual
  3  UNION ALL SELECT 'person1' person, 'day2' day, 'Y' flag FROM dual
  4  UNION ALL SELECT 'person1' person, 'day3' day, 'Y' flag FROM dual
  5  UNION ALL SELECT 'person1' person, 'day4' day, 'N' flag FROM dual
  6  UNION ALL SELECT 'person1' person, 'day5' day, 'N' flag FROM dual
  7  UNION ALL SELECT 'person1' person, 'day6' day, 'Y' flag FROM dual
  8  UNION ALL SELECT 'person1' person, 'day7' day, 'Y' flag FROM dual
  9  UNION ALL SELECT 'person1' person, 'day8' day, 'Y' flag FROM dual
 10  )
 11  SELECT person, DAY, flag, SUM(gap) over (PARTITION BY person
 12                                           ORDER BY DAY) grp
 13    FROM (SELECT person, DAY, flag,
 14                 CASE WHEN flag = lag(flag) over (PARTITION BY person
 15                                                  ORDER BY DAY)
 16                      THEN 0
 17                      ELSE 1
 18                 END gap
 19            FROM DATA);

PERSON  DAY  FLAG        GRP
------- ---- ---- ----------
person1 day1 Y             1
person1 day2 Y             1
person1 day3 Y             1
person1 day4 N             2
person1 day5 N             2
person1 day6 Y             3
person1 day7 Y             3
person1 day8 Y             3



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. ubah tabel ubah kolom di database Oracle

  2. Bagaimana menangani detik kabisat di Oracle

  3. Membuat Aplikasi Java di Oracle JDeveloper, Bagian 1

  4. seperti apa indeks B-tree pada lebih dari 1 kolom?

  5. Fungsi ASIN() di Oracle