1

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

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

例如这个:

| 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 复制记录?

4

2 回答 2

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
于 2013-07-15T18:22:58.330 回答
-1

SELECT item.* FROM (SELECT LEVEL l FROM DUAL CONNECT BY LEVEL <= maximum_number) 数据,item WHERE data.l <= item.quantity ORDER BY item.id

于 2013-07-15T15:00:43.480 回答