1

我正在处理按项目编号和计数分组的数据。需要将带有 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

我需要这样格式化的数据(动态地对 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

出于某种原因,我无法用一种干净的方式(或任何方式)来解决这个问题。

4

3 回答 3

4

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

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);

编辑:

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

于 2012-04-12T18:50:42.040 回答
3

您可以使用下面的查询来避免递归,我认为会更有效率。此处,表 N 是任何行数至少与最大 CountOfItems 值一样多的表。

这是一个罕见的查询示例,其中没有 ORDER BY 的 TOP 不是一个坏主意。

select
  OwnerNumber,
  ItemCode,
  ItemNumber
from t
cross apply (
  select top (CountOfItems) null
  from N
 ) as N(c)
于 2012-04-12T20:25:23.763 回答
3

嗯....我想我喜欢递归 CTE:

WITH Data (OwnerNumber, ItemCode, ItemNumber, CountOfItems) as (
           SELECT OwnerNumber, ItemCode, ItemNumber, CountOfItems
           FROM OriginalTable
           UNION ALL
           SELECT OwnerNumber, ItemCode, ItemNumber, CountOfItems - 1
           FROM Data
           WHERE CountOfItems > 1)
SELECT OwnerNumber, ItemCode, ItemNumber
FROM Data
ORDER BY OwnerNumber, ItemCode, ItemNumber
于 2012-04-12T18:49:32.400 回答