如何在外部应用中使用while循环 - SQL Server

时间:2016-10-30 22:01:58

标签: sql-server sql-server-2008 tsql

我需要做什么:

  • 根据最早到期日确定销售订单中每个零件的未清工作
  • 条件:列出满足销售订单需求的最早的工作/工作(针对特定部分)。如果最高职位不满足所需数量,请选择下一个工作..

销售订单表 - 名称: SalesOrder

SO   | Part    |    SO_Qty   |
--------------------------
SO1  | Part1   |    5   |
SO2  | Part2   |    7   |
SO3  | Part3   |    4   |

工作订单表 - 名称: JobOrder - ((所有打开的工作 - 按Due_Date排序)

SO  | Part  | JO   | JO_Qty | Due_Date |
-----------------------------------------
SO1 | Part1 | JO1a |    6   | 11/01/16 |
SO1 | Part1 | JO1b |    5   | 11/10/16 |
SO2 | Part2 | JO2a |    3   | 11/01/16 |
SO2 | Part2 | JO2b |    2   | 11/08/16 |
SO2 | Part2 | JO2c |    9   | 11/18/16 |
SO3 | Part3 | JO3a |    4   | 12/05/16 |
SO3 | Part3 | JO3b |    2   | 12/20/16 |

结果表(这是我想看到的......)

SO  | Part  | SO_Qty | JO   | JO_Qty | Due_Date |
-------------------------------------------------
SO1 | Part1 |   5    | JO1a |   6    | 11/01/16 |
SO2 | Part2 |   7    | JO2a |   3    | 11/01/16 |
SO2 | Part2 |   7    | JO2b |   2    | 11/08/16 |
SO2 | Part2 |   7    | JO2c |   9    | 11/18/16 |
SO3 | Part3 |   4    | JO3a |   4    | 12/05/16 |

我尝试过:

 Select OD.*, SQ.jo, SQ.jo_qty, SQ.due_date
 From SalesOrder AS OD
 OUTER APPLY (Select jo, jo_qty, due_date
              From JobOrder as JO   
              Where JO.so = OD.so AND JO.part = OD.part) AS SQ

无论作业单数量如何,都会返回所有匹配的作业单。那不是我想要的......

我的问题:我可以在子查询中使用while循环来过滤记录吗?

提前感谢您的帮助..

您可以使用的脚本:

;WITH SalesOrder AS (
SELECT *
FROM (VALUES
('SO1', 'Part1', 5),
('SO2', 'Part2', 7),
('SO3', 'Part3', 4)
) as t(SO, Part, SO_Qty)
), JobOrder AS (
SELECT *
FROM (VALUES
('SO1', 'Part1', 'JO1a', 6 , '11/01/16'),
('SO1', 'Part1', 'JO1b', 5 , '11/10/16'),
('SO2', 'Part2', 'JO2a', 3 , '11/01/16'),
('SO2', 'Part2', 'JO2b', 2 , '11/08/16'),
('SO2', 'Part2', 'JO2c', 9 , '11/18/16'),
('SO3', 'Part3', 'JO3a', 4 , '12/05/16'),
('SO3', 'Part3', 'JO3b', 2 , '12/20/16')
) as t(SO, Part, JO, JO_Qty, Due_Date)
)

1 个答案:

答案 0 :(得分:0)

我认为你可以使用递归CTE解决它 - 它有点长,但这是我的最大努力...

WITH j AS
(
    SELECT
     jo.SO
    ,so.Part
    ,so.SO_Qty
    ,jo.JO
    ,jo.JO_Qty
    ,jo.Due_Date
    ,ROW_NUMBER() OVER(ORDER BY jo.SO, Due_Date) AS RowID
    FROM #jobOrder jo
    JOIN #SalesOrder so
    ON jo.SO = so.SO
    AND jo.Part = so.Part
)
,rCTE AS
(
    SELECT
     RowID
    ,SO
    ,Part
    ,SO_Qty
    ,JO
    ,JO_Qty
    ,Due_Date
    ,JO_Qty - SO_Qty AS Diff
    FROM j
    WHERE RowID = 1

    UNION ALL

    SELECT
     j.RowID
    ,r.SO
    ,j.Part
    ,j.SO_Qty
    ,j.JO
    ,j.JO_Qty
    ,j.Due_Date
    ,CASE   WHEN j.Part != r.Part OR (j.Part = r.Part AND Diff < 0) THEN
                j.JO_Qty - j.SO_Qty
            END
    FROM rCTE r
    JOIN j
    ON j.RowID = r.RowID + 1
)
SELECT
 *
FROM rCTE
WHERE Diff IS NOT NULL;