Question

Given this starting 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
), 

How do I generate a result set that has as many rows per row in Section as there are numbers between StartUnit and EndUnit (inclusive), with values ascending?

That is, I'd like to see a result set of:

Section  Unit
1        1
1        2
1        3
1        4
1        5
2        0
2        1
2        2
3        1

Note that some of the values in the Sections CTE will be parameters, so it's not as simple as extending my UNIONs to the right number.

UPDATE

I've thought about this a little more and have another guideline. I'll take any answer that's correct, but was particularly hoping for someone to possibly show how to do this with CONNECT BY PRIOR and without an extra CTE in the middle...

I realized I could change the CTE to this:

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
)

But I'm leaning away from that here because it may come from a table rather than be selected from DUAL. So let's assume the Sections CTE is in fact a simple query from a table, something like:

SELECT Section, StartUnit, EndUnit FROM SectionData WHERE CallerID = 7

And the original question still stands.

Was it helpful?

Solution

Try this:

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;

You may want to adjust the value of 1000 I used.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top