创建整数视图?

发布于 2024-12-14 22:31:59 字数 221 浏览 1 评论 0原文

我有一张名为 A 的表。它只有一条记录和一个字段。它是一个名为 number 的整数。 我想创建一个包含 A.number 记录的视图,每条记录都是小于 A.number 的数字之一。

例如:

选择A.号码-----> 5

视图应该显示 5 条记录 0 1 2 3 4

P.S:这是一个真正的问题,我简化了很多。真正的问题就像将固定期间的预算划分到每一天。

I have a table named A. it has only one record with one field. It is an integer named number.
I want to create a view that have A.number records, each are one of the numbers less than A.number.

For example:

select A.number -----> 5

the view should show 5 records 0 1 2 3 4

P.S: This is a real problem that I simplified it a lot. The real problem is like dividing a budget in a fixed period to each day.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

叶落知秋 2024-12-21 22:31:59

这听起来有点像家庭作业,所以我对直接提供代码持谨慎态度。

不过,我可以为如何解决这个问题提供指导。您使用递归 CTE,其中每次迭代都会在前一次迭代的基础上加一。如果您要检查数字 > ,请务必设置 MAXRECURSION 选项。 101. 您可以使用标量子查询将视图键入原始表:


WITH numbers ( n ) AS (
    SELECT 0 UNION ALL
    SELECT 1 + n FROM numbers WHERE n < (select number from a) -1)
SELECT n FROM numbers
OPTION ( MAXRECURSION 500) --example

This sounds a bit like it might be homework, so I'm wary of providing the code outright.

I can give a pointer for how to solve the question, though. You use a recursive CTE where each iteration adds one to the previous iteration. Just be sure to set the MAXRECURSION option if you'll be checking numbers > 101. You can use a scalar sub query to key the view to the original table:


WITH numbers ( n ) AS (
    SELECT 0 UNION ALL
    SELECT 1 + n FROM numbers WHERE n < (select number from a) -1)
SELECT n FROM numbers
OPTION ( MAXRECURSION 500) --example
孤芳又自赏 2024-12-21 22:31:59

如果您的餐桌数量<< 2048 并且您在 SQL Server 上,这对您有用:

CREATE VIEW MyView AS
   SELECT number
   FROM master..spt_values
   WHERE type = 'p'
      AND number < (SELECT value FROM yourTable)

或者,如果您需要更高的限制,或者不在为您提供此功能的 SQL Server 上,您可以考虑创建自己的具有适当大小的 Numbers 表以适合您的应用程序。 这里是一篇博客文章的链接,内容涉及“数字表”方便。

If the number of your table will be < 2048 and you are on SQL Server, this will work for you:

CREATE VIEW MyView AS
   SELECT number
   FROM master..spt_values
   WHERE type = 'p'
      AND number < (SELECT value FROM yourTable)

Alternatively you could consider creating your own Numbers table with an appropriate size to suit your application if you require a higher limit, or are not on SQL Server that has this provided to you. Here is a link to a blog post on the idea of having a "Numbers table" handy.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文