gpt4 book ai didi

sql - 根据列值生成行

转载 作者:行者123 更新时间:2023-12-03 22:13:23 25 4
gpt4 key购买 nike

我的数据库中的一个表包含带有申请编号和其他相关信息的行。我正在尝试创建第二个表(用 INSERT INTO 语句填充)来复制这些行并根据 QuantityOrdered 中的值添加一个系列值。柱子。

例如,第一个表如下所示:

+-------------+----------+
| Requisition | Quantity |
+-------------+----------+
| 10001_01_AD | 4 |
+-------------+----------+

我希望输出如下:
+-------------+----------+----------+
| Requisition | Quantity | Series |
+-------------+----------+----------+
| 10001_01_AD | 4 | 1 |
| 10001_01_AD | 4 | 2 |
| 10001_01_AD | 4 | 3 |
| 10001_01_AD | 4 | 4 |
+-------------+----------+----------+

我一直在尝试使用 Row_Number()对值进行排序,但它根据 Requisition 值的实例对行进行编号,而不是基于 Quantity 值。

最佳答案

您需要递归方式:

with t as (
select Requisition, 1 as start, Quantity
from table
union all
select Requisition, start + 1, Quantity
from t
where start < Quantity
)
select Requisition, Quantity, start as Series
from t;

但是,默认情况下它仅限于 100 Quantities , 如果您有更多,则需要使用 option (maxrecursion 0) 指定查询提示.

关于sql - 根据列值生成行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52744203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com