Oracle
 sql >> Base de données >  >> RDS >> Oracle

obtenir la liste des nombres entre deux colonnes

si vous vouliez que les valeurs soient séparées par des virgules, vous pouvez le faire (ou si sur 11gr2, utilisez listAgg )

WITH NUMS AS(
     SELECT 10 STARTNR  , 15 ENDNR  FROM DUAL UNION
    SELECT 18 STARTNR  , 22 ENDNR  FROM DUAL UNION
    SELECT 34 STARTNR  , 50 ENDNR  FROM DUAL )       , 
 NUMSBETWEEN AS(
     SELECT distinct (level + startnr)-1 seq , startnr, endnr
       FROM NUMS
      CONNECT BY (LEVEL +STARTNR ) <= ENDNR+1
      )
SELECT startnr,
       LTRIM(MAX(SYS_CONNECT_BY_PATH(seq,','))
       KEEP (DENSE_RANK LAST ORDER BY curr),',') AS seq
FROM   (SELECT startnr,
               seq,
               ROW_NUMBER() OVER (PARTITION BY startnr ORDER BY seq) AS curr,
               ROW_NUMBER() OVER (PARTITION BY startnr ORDER BY seq) -1 AS prev
        FROM   numsBetween)
GROUP BY startnr
CONNECT BY prev = PRIOR curr AND startnr = PRIOR startnr
START WITH CURR = 1;

STARTNR SEQ

10 10,11,12,13,14,15
18 18,19,20,21,22
34 34,35,36,37,38,39,40,41,42,43 ,44,45,46,47,48,49,50