查询以区分库存,销售订单,退出中的记录

时间:2016-06-07 01:25:22

标签: sql sql-server

我有2个表格和lot_transactions

很多

lotID       |   salesorderdocline   |         
-------------------------------------------------
72266414    |   15          |    
72266415    |   0           |    
72266416    |   0           |    

lot_transactions

lotID       |   salesorderdocline   |   trstypeid   |   trsdate  
----------------------------------------------------------------------------------------  
72266414    |   0           |   400     |       19-05-2016   
72266414    |   11          |   1104    |       20-05-2016  
72266414    |   11          |   132     |       24-05-2016  
72266414    |   0           |   133     |       25-05-2016  
72266414    |   15          |   1104    |       30-05-2016  
72266415    |   0           |   400     |       04-02-2016  
72266416    |   0           |   400     |       03-02-2016  
72266416    |   10          |   1104    |       05-02-2016  
72266416    |   10          |   400     |       06-02-2016  
72266416    |   10          |   132     |       08-02-2016  
72266416    |   0           |   133     |       09-02-2016  

输出

lotid       |   Stockstatus  
---------------------------------------- 
72266414    |   Salesorder  
72266415    |   Instock  
72266416    |   Dropout  
获取销售订单,Instock和Dropout 的标准

72266414在销售订单中,因为如果我们检查salesorderdocline它已从0 - 11 -0 - 15更改 72266415在Instock中,因为salesorderdocline为0 72266416处于Dropout状态,因为salesorderdocline已从0-10-0更改。

如果salesorderdocline = 0则为库存。 如果大于0而不是销售订单 lot_transactions 是我们可以查看特定批次的所有交易的表格 lot 是仅显示当前状态的表

我正在使用MSSQL数据库

1 个答案:

答案 0 :(得分:1)

SELECT l.lotID,
       Stockstatus = case when l.salesorderdocline > 0
                          then 'SalesOrder'
                          when l.salesorderdocline = 0
                          and  not exists 
                               (
                                   select *
                                   from   lot_transactions x
                                   where  x.lotID = l.lotID
                                   and    x.salesorderdocline > 0
                               )
                          then 'Instock'
                          else 'Dropout'
                          end
FROM   lot l