How can I expand out a row into multiple row result set?

后端 未结 3 681
感情败类
感情败类 2020-12-18 07:33

I have a table that I\'m trying to break out each row into one or more rows based on the second column value. Like this:

table (id, pcs):
ABC   3
DEF   1
GH         


        
3条回答
  •  长情又很酷
    2020-12-18 08:02

    You can use a recursive CTE:

    ;WITH CTE AS
    (
        SELECT *
        FROM YourTable
        UNION ALL 
        SELECT id, pcs-1
        FROM CTE
        WHERE pcs-1 >= 1
    )
    SELECT *
    FROM CTE
    ORDER BY id, pcs
    OPTION(MAXRECURSION 0)
    

    Here is a demo for you to try.

提交回复
热议问题