SQL根据数量重复一行

时间:2013-07-15 14:38:45

标签: sql crystal-reports

我需要创建一个SQL视图,我可以将其作为XML数据集传递给Crystal Reports。

我需要根据数量复制记录(产品项目):

E.g。这样:

| Product ID | Product Name | Quantity
-----------------------------------------
    0001        Product 1        5
    0002        Product 2        3

成为这个:

| Product ID | Product Name | Quantity
-----------------------------------------
    0001        Product 1        5
    0001        Product 1        5
    0001        Product 1        5
    0001        Product 1        5
    0001        Product 1        5
    0002        Product 2        3
    0002        Product 2        3
    0002        Product 2        3

如何根据数量使用SQL复制记录?

2 个答案:

答案 0 :(得分:3)

以下是基于递归公用表表达式的解决方案。

WITH CTE(ProductID, RowIndex) AS
    (
        SELECT
            ProductID
            ,Quantity AS RowIndex
        FROM [TableName]
        WHERE Quantity > 0
        UNION ALL
        SELECT
            ProductID
            ,RowIndex - 1
        FROM CTE
        WHERE RowIndex - 1 > 0
    )

SELECT Tbl1.*
FROM [TableName] AS Tbl1
INNER JOIN CTE AS Tbl2
    ON Tbl1.ProductID = Tbl2.ProductID
ORDER BY Tbl1.ProductID

要使用上述代码,只需将TableName替换为您的表名。

测试表

| ProductID | ProductName | Quantity |
--------------------------------------
    0001       Product 1        5
    0002       Product 2        3
    0003       Product 3        2
    0004       Product 4        0

执行代码后的结果

| ProductID | ProductName | Quantity |
--------------------------------------
    0001       Product 1        5
    0001       Product 1        5
    0001       Product 1        5
    0001       Product 1        5
    0001       Product 1        5
    0002       Product 2        3
    0002       Product 2        3
    0002       Product 2        3
    0003       Product 3        2
    0003       Product 3        2

答案 1 :(得分:-1)

选择项目。*     FROM(SELECT LEVEL l                 来自双重           CONNECT BY LEVEL< = largest_number)数据,          项目    WHERE data.l< = item.quantity ORDER BY item.id