反转/吹出 GROUP BY

dev*_*ter 2 sql t-sql sql-server-2008

我正在处理按项目编号和计数分组的数据。每个带有 a 的记录都count > 2需要分解为单独的记录,并在该级别与不同的数据集进行比较。

数据看起来像这样(它被困在这种格式中。这是客户发送它的唯一方式。):

OwnerNumber ItemCode    ItemNumber  CountOfItems
1234    Item1   Item1-001   3
1234    Item1   Item1-002   1
1234    Item1   Item1-003   2
1234    Item2   Item2-001   1
Run Code Online (Sandbox Code Playgroud)

我需要这样格式化的数据(动态地不对 CountOfItems 的值进行硬编码):

OwnerNumber ItemCode    ItemNumber  
1234    Item1   Item1-001
1234    Item1   Item1-001
1234    Item1   Item1-001
1234    Item1   Item1-002
1234    Item1   Item1-003
1234    Item1   Item1-003
1234    Item2   Item2-001
Run Code Online (Sandbox Code Playgroud)

出于某种原因,我无法以一种干净的方式(或任何方式)来做到这一点。

ANi*_*sus 5

您可以使用通用表表达式进行管理

WITH CTE AS (
    SELECT OwnerNumber,ItemCode,ItemNumber,CountOfItems FROM table

    UNION ALL SELECT OwnerNumber,ItemCode,ItemNumber,CountOfItems-1
    FROM CTE
    WHERE CountOfItems >= 2
)
SELECT OwnerNumber,ItemCode,ItemNumber
FROM CTE
ORDER BY ItemNumber
OPTION (MAXRECURSION 0);
Run Code Online (Sandbox Code Playgroud)

编辑:

添加MAXRECURSION用于处理 CountOfItems 超过 Dev_etter 指出的默认最大递归的情况