sql >> Database teknologi >  >> RDS >> Oracle

Få optælling af på hinanden følgende dage, der opfylder et givet kriterium

Denne forespørgsel vil give tællingerne for hver række:

SELECT allocation, d, count(*) OVER (PARTITION BY allocation, part ORDER BY d) AS c
FROM (
  SELECT allocation, d,
         d - row_number() OVER (PARTITION BY allocation ORDER BY d) AS part
  FROM t
)
ORDER BY d;
 

Du kan derefter filtrere på den for at finde antallet af en given række:

SELECT c
FROM (
  SELECT allocation, d, count(*) OVER (PARTITION BY allocation, part ORDER BY d) AS c
  FROM (
    SELECT allocation, d,
           d - row_number() OVER (PARTITION BY allocation ORDER BY d) AS part
    FROM t
  )
)
WHERE d = DATE '2015-01-05';
 

Forklaring:

Den afledte tabel bruges til at beregne forskellige "partitioner" part for hver dato og tildeling:

  SELECT allocation, d,
         d - row_number() OVER (PARTITION BY allocation ORDER BY d) AS part
  FROM t
 

Resultatet er:

allocation d part -------------------------------- Same 01.01.15 31.12.14 Good 02.01.15 01.01.15 Same 03.01.15 01.01.15 Same 04.01.15 01.01.15 Same 05.01.15 01.01.15 Good 06.01.15 04.01.15

Den konkrete dato produceret af part er irrelevant. Det er bare en dato, der vil være den samme for hver "gruppe" af datoer inden for en tildeling. Du kan derefter tælle antallet af identiske værdier for (allocation, part) ved at bruge count(*) over(...) vinduesfunktion:

SELECT allocation, d, count(*) OVER (PARTITION BY allocation, part ORDER BY d) AS c
FROM (...)
ORDER BY d;
 

for at producere dit ønskede resultat.

Data

Jeg har brugt følgende tabel til eksemplet:

CREATE TABLE t AS (
  SELECT DATE '2015-01-01' AS d, 'Same' AS allocation FROM dual UNION ALL
  SELECT DATE '2015-01-02' AS d, 'Good' AS allocation FROM dual UNION ALL
  SELECT DATE '2015-01-03' AS d, 'Same' AS allocation FROM dual UNION ALL
  SELECT DATE '2015-01-04' AS d, 'Same' AS allocation FROM dual UNION ALL  
  SELECT DATE '2015-01-05' AS d, 'Same' AS allocation FROM dual UNION ALL
  SELECT DATE '2015-01-06' AS d, 'Good' AS allocation FROM dual
);
 


  1. Implementering af database fra kildekontrol

  2. Anslået antal rækker, der skal læses

  3. Hvordan bruger man regex i MySQL?

  4. COPY kommando:kopier kun specifikke kolonner fra csv