选择不适用于库存数量总和的情况

时间:2018-06-10 23:42:16

标签: sql

我有两张桌子:需求表&库存表。

第一张表:所需数量

| Ship From | Material | Req Date  | Req Quantity | Fulfill (Y/N)? |
|-----------|----------|-----------|--------------|----------------|
|        21 | Mat1     | 7/1/2018  |           46 |                |
|        21 | Mat1     | 8/19/2018 |           33 |                |
|        21 | Mat1     | 9/2/2018  |           99 |                |
|        21 | Mat1     | 9/2/2018  |            4 |                |
|       106 | Mat1     | 9/16/2018 |           92 |                |
|       106 | Mat1     | 8/19/2018 |          126 |                |
|       457 | Mat2     | 8/19/2018 |          126 |                |
|       457 | Mat2     | 9/10/2018 |          126 |                |
|       457 | Mat2     | 9/10/2018 |          126 |                |
|       457 | Mat2     | 9/10/2018 |           24 |                |
|       478 | Mat2     | 9/2/2018  |           52 |                |
|       478 | Mat2     | 9/10/2018 |           73 |                |
|       478 | Mat2     | 9/10/2018 |           18 |                |
|       478 | Mat2     | 9/16/2018 |           30 |                |

第二张表:可用库存

 ----------- ---------- -------------------- --------------- 
  Ship From   Material   Inv Available Date   Available Qty  
 ----------- ---------- -------------------- --------------- 
         21   Mat1       6/15/2018                       46  
         21   Mat1       6/15/2018                       33  
         21   Mat1       7/2/2018                        99  
         21   Mat1       10/2/2018                        4  
        106   Mat1       10/16/2018                      92  
        106   Mat1       7/19/2018                      126  
        457   Mat2       8/19/2018                      126  
        457   Mat2       8/10/2018                      126  
        478   Mat2       9/16/2018                       30  
        478   Mat2       10/2/2018                       52  

需要在Inv可用日期或之前检查第二个表格中是否有足够的库存(总和(可用数量))并在table1上标记我们是否可以履行订单。

请注意,对于表1中履行的订单,我们需要减少表2中的数量总和。

我在table1中有70k行,在table2中有600k行。

Select
    Y1.Material,
    Y1.[Order Qty],
    Y1.[Ship From],
    Y1.[Code Date] as Req_date,
    I1.[Code Date] as Inv_date,
    (SELECT CASE WHEN (Select SUM(I1.Quantity) as sum_qty FROM YOTC_ALL Y1, Inventory I1 WHERE Y1.Material = I1.Material AND Y1.[Ship From] = I1.[Ship From] AND 
    Y1.[Code Date] > = I1.[Code Date]) > Y1.[Order Qty]) THEN "Y" ELSE "N"
FROM
    YOTC_ALL Y1,
    Inventory I1
WHERE
    Y1.Material = I1.Material AND
    Y1.[Ship From] = I1.[Ship From] AND
    Y1.[Code Date] > = I1.[Code Date]
GROUP BY
    I1.[Code Date],
    Y1.Material,
    Y1.[Order Qty],
    Y1.[Ship From],
    Y1.[Code Date];

我已经尝试过上述查询,但似乎无法让它发挥作用。请帮助!!!

0 个答案:

没有答案