数据库中的一个表包含带有请购单编号和其他相关信息的行。我正在尝试创建第二个表(填充有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()
对值进行排序,但是它是根据“申请”值的实例而不是“数量”值对行进行编号的。
答案 0 :(得分:2)
您需要递归方式:
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)
指定查询提示。
答案 1 :(得分:1)
一种简单的方法使用递归CTE:
with cte as (
select requsition, quantity, 1 as series
from t
union all
select requsition, quantity, 1 + series
from t
where lev < quantity
)
select requsition, quantity, series
from cte;
使用默认设置时,该数量最多为100。对于更大的数量,您可以向查询中添加option (maxrecursion 0)
。
答案 2 :(得分:1)
非递归方式:
SELECT *
FROM tab t
CROSS APPLY (SELECT n
FROM (SELECT ROW_NUMBER() OVER(ORDER BY 1/0) AS n
FROM master..spt_values s1) AS sub
WHERE sub.n <= t.Quantity) AS s2(Series);