Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
674 views
in Technique[技术] by (71.8m points)

sql - Generating Rows Based on Column Value

One of my tables in my database contains rows with requisition numbers and other related info. I am trying to create a second table (populated with an INSERT INTO statement) that duplicates these rows and adds a series value based on the value in the QuantityOrdered column.

For example, the first table is shown below:

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

and I would like the output to be as follows:

+-------------+----------+----------+
| Requisition | Quantity |  Series  |
+-------------+----------+----------+
| 10001_01_AD |     4    |     1    |
| 10001_01_AD |     4    |     2    |
| 10001_01_AD |     4    |     3    |
| 10001_01_AD |     4    |     4    |
+-------------+----------+----------+

I've been attempting to use Row_Number() to sequence the values but it's numbering rows based on instances of Requisition values, not based on the Quantity value.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need recursive way :

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; 

However, by default it has limited to only 100 Quantities, if you have a more then you need to specify the query hint by using option (maxrecursion 0).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...