3

我有这样的 CTE:

WITH CTE(PartNum, RowIndex) AS
(
        -- Anchor Member
        SELECT
            PartNum
            ,CAST(OurQty AS INT) AS RowIndex
        FROM dbo.RcvDtl
        WHERE OurQty > 0
        UNION ALL
        -- Recursive Member
        SELECT
            PartNum
            ,RowIndex - 1
        FROM CTE
        WHERE RowIndex - 1 > 0
)
SELECT 
    tbl1.PONum, tbl1.PartNum, 
    CAST(tbl1.OurQty AS INT) AS Quantity, 
    tbl2.RowIndex AS RowIndex
FROM 
    dbo.RcvDtl AS Tbl1
INNER JOIN 
    CTE AS Tbl2 ON Tbl1.PartNum = Tbl2.PartNum
WHERE 
    tbl1.PONum = '63'
ORDER BY 
    Tbl1.PartNum OPTION(MAXRECURSION 1000)

在下表中运行:

| PartNum | Quantity
---------------------
  10050857    6
  10050886    10
  10050923    24

查询的想法是根据其数量复制记录(PartNum)。该查询将第一个 PartNum '10050857' 复制了 46 条记录 (6+(6+10+24)),而它应该只复制 6 次,第二个 PartNum '10050886' 按预期复制了 10 条记录,最后的部分 num '10050923'正如预期的那样,增加了 24 条记录。

为什么查询通过累积第一条记录之后的记录来复制第一条记录?

4

1 回答 1

1

我不得不稍微更改名称,但您的 CTE 确实有效:

WITH CTE(PartNum, RowIndex) AS
(
        -- Anchor Member
        SELECT
            PartNum
            ,CAST(OurQty AS INT) AS RowIndex
        FROM dbo.RcvDtl
        WHERE OurQty > 0
        UNION ALL
        -- Recursive Member
        SELECT
            PartNum
            ,RowIndex - 1
        FROM CTE
        WHERE RowIndex - 1 > 0
)
SELECT CTE.PartNum, dbo.RcvDtl.OurQty, CTE.RowIndex from CTE INNER JOIN dbo.RcvDtl
ON CTE.PartNum = dbo.RcvDtl.PartNum
order by PartNum,RowIndex

只需再次检查您的代码,它将起作用。技巧也不错,我喜欢一点 CTE!

于 2013-07-27T03:56:13.457 回答