简体   繁体   English

根据列值将行拆分为多行

[英]Split a row into multiple rows based on a column value SQL

I have the following "Order Table" : 我有以下“订单表”:

    Item        Quantity
    pencil      2
    pen         1
    Notebook    4

I need the result like : 我需要这样的结果:

  Item        Quantity
  pencil      1
  pencil      1
  pen         1
  Notebook    1
  Notebook    1
  Notebook    1
  Notebook    1

You didn't specify which RDBMS you are using, so how you generate the numbers will depend on that (maybe a recursive CTE for SQL Server, using DUAL for Oracle, etc.). 您没有指定要使用的RDBMS,因此如何生成数字将取决于此(可能是SQL Server的递归CTE,Oracle的DUAL等)。 I've only written code to handle the data that you've shown, but you'll obviously need to account for numbers larger than four in the final solution. 我只编写了代码来处理您显示的数据,但是显然在最终解决方案中您需要考虑大于四的数字。

SELECT
    MT.sr_no,
    MT.item_name,
    1 AS quantity
FROM
    My_Table MT
INNER JOIN
    (
        SELECT 1 AS nbr UNION ALL SELECT 2 AS nbr UNION ALL
        SELECT 3 AS nbr UNION ALL SELECT 4 AS nbr
    ) N ON N.nbr <= MT.quantity

You can use the recursive query using common table expression to generate number duplicate rows according to the quantity field as below 您可以使用公共表表达式使用递归查询,根据数量字段生成数量重复的行,如下所示

WITH cte (sno,item,quantity,rnum)
AS
(
    SELECT sno,item,quantity, 1 as rnum
    FROM [Order]

    UNION ALL

    SELECT cte.sno,cte.item,cte.quantity, rnum+1
    FROM [Order] JOIN cte ON [Order].sno = cte.sno
    AND cte.rnum < [Order].quantity
)
SELECT item,1 AS Quantity 
FROM cte 
ORDER BY sno

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM