Correlated fila generano query in Oracle
-
15-10-2019 - |
Domanda
Dato questo inizio CTE:
WITH Sections AS (
SELECT 1 Section, 1 StartUnit, 5 EndUnit FROM DUAL
UNION ALL SELECT 2, 0, 2 FROM DUAL
UNION ALL SELECT 3, 1, 1 FROM DUAL
),
Come faccio a generare un set di risultati che ha come molte righe per riga nella sezione in quanto vi sono numeri tra StartUnit e EndUnit (compreso), con valori ascendente?
Cioè, mi piacerebbe vedere un set di risultati di:
Section Unit
1 1
1 2
1 3
1 4
1 5
2 0
2 1
2 2
3 1
Si noti che alcuni dei valori nelle sezioni CTE sarà parametri, quindi non è così semplice come estendere i miei sindacati per il numero giusto.
Aggiorna
Ho pensato a questo un po 'di più e avere un altro orientamento. Prenderò qualsiasi risposta che è corretto, ma è stato soprattutto sperando che qualcuno forse mostrare come fare questo con CONNECT previa e senza un CTE in più in mezzo ...
ho capito che potevo cambiare il CTE a questo:
WITH Sections AS (
SELECT 1 Section, LEVEL Unit FROM DUAL CONNECT BY LEVEL <= 5
UNION ALL SELECT 2, LEVEL - 1 FROM DUAL CONNECT BY LEVEL <= 3
UNION ALL SELECT 3, 1 FROM DUAL CONNECT BY LEVEL <= 1
)
Ma io sono appoggiato via da quella qui perché può venire da una tabella piuttosto che essere scelto dal DUAL. Quindi supponiamo che le Sezioni CTE è in realtà una semplice query da una tabella, qualcosa come:
SELECT Section, StartUnit, EndUnit FROM SectionData WHERE CallerID = 7
E la domanda iniziale si è fermato.
Soluzione
Prova questo:
WITH Sections AS (
SELECT 1 Section, 1 StartUnit, 5 EndUnit FROM DUAL
UNION ALL SELECT 2, 0, 2 FROM DUAL
UNION ALL SELECT 3, 1, 1 FROM DUAL
),
Numbers AS (
SELECT ROWNUM-1 n
FROM DUAL
CONNECT BY LEVEL < 1000
)
select section, n
from sections, numbers
where n between startunit and endunit
order by section, n;
Si può decidere di regolare il valore 1000 che ho usato.