Oracle中相关的行生成查询

时间:2011-01-21 00:41:04

标签: sql oracle11g simplification connect-by

鉴于此开始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
), 

如何在Section中生成每行包含尽可能多行的结果集,因为StartUnit和EndUnit(包括)之间有数字,值是否会升高?

也就是说,我希望看到一个结果集:

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

请注意,章节CTE中的某些值将是参数,因此不像将UNION扩展到正确的数字那么简单。

更新

我已经考虑了这个,并有另一个指南。我会采取任何正确的答案,但特别希望有人能够通过CONNECT BY PRIOR展示如何做到这一点,并且中间没有额外的CTE ......

我意识到我可以将CTE更改为:

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
)

但我偏离这里,因为它可能来自一张桌子,而不是从DUAL中选出。因此,我们假设章节CTE实际上是一个来自表格的简单查询,例如:

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

最初的问题仍然存在。

1 个答案:

答案 0 :(得分:0)

试试这个:

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;

您可能需要调整我使用的1000的值。