Sqlserver
 sql >> Teknologi Basis Data >  >> RDS >> Sqlserver

grup sql hanya dengan baris yang berurutan

Ini dikenal sebagai masalah "pulau". Menggunakan pendekatan Itzik Ben Gan:

;WITH YourTable AS
(
SELECT 1 AS N, 'A' AS C UNION ALL
SELECT 2 AS N, 'A' AS C UNION ALL
SELECT 3 AS N, 'A' AS C UNION ALL
SELECT 4 AS N, 'B' AS C UNION ALL
SELECT 5 AS N, 'B' AS C UNION ALL
SELECT 6 AS N, 'B' AS C UNION ALL
SELECT 7 AS N, 'A' AS C UNION ALL
SELECT 8 AS N, 'A' AS C
),
     T
     AS (SELECT N,
                C,
                DENSE_RANK() OVER (ORDER BY N) - 
                DENSE_RANK() OVER (PARTITION BY C ORDER BY N) AS Grp
         FROM   YourTable)
SELECT COUNT(*),
       C
FROM   T
GROUP  BY C,
          Grp 
ORDER BY MIN(N)


  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 terbaik untuk mengonversi dan memvalidasi string tanggal

  2. Cara sederhana untuk mengubah urutan kolom dan baris dalam SQL?

  3. Temukan Tipe Data Kolom yang Dikembalikan dalam Kumpulan Hasil di SQL Server

  4. Operator Ampersand (&) dalam SQL Server WHERE Clause

  5. Ganti nama Akun SA di SQL Server (Contoh T-SQL)