Oracle 中的关联行生成查询
给定这个起始 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
),
如何生成一个结果集,该结果集在部分中每行的行数与 StartUnit 和 EndUnit(含)之间的数字一样多,并且值递增?
也就是说,我希望看到以下结果集:
Section Unit
1 1
1 2
1 3
1 4
1 5
2 0
2 1
2 2
3 1
请注意,Sections 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
原来的问题仍然存在。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试这个:
你可能想调整我使用的 1000 的值。
Try this:
You may want to adjust the value of 1000 I used.