如何使用相同的服务标签获得售后剩余库存?

时间:2015-09-09 06:05:29

标签: sql sql-server-2008-r2

表1

Stockno|StartDate|ServiceTag|Modelno
123     2015-08-01  ABC      Inspiron
123     2015-06-01  DEF      Inspiron
123     2015-08-01  GHI      Inspiron
123     2015-08-01  JKL      Inspiron
456     2015-08-01  MNO      Galaxy
456     2015-07-01  PQR      Galaxy
456     2015-08-01  STU      Galaxy
456     2015-08-01  VWX      Galaxy
456     2015-08-01  ABC      Galaxy

TABLE_2

Stockno |TransDate|TransType|ServiceTag|Modelno                                  
123      2015-08-04 2100      ABC       Inspiron
123      2015-08-19 2100      GHI       Inspiron
456      2015-08-25 2100      STU       Galaxy
123      2015-07-25 2100      DEF       Inspiron

我有两张桌子。 Table_1有库存。 Table_2是卖出的股票。

我希望剩余库存售后。我写了下面的查询,它工作正常,但问题是它没有返回Galaxy与服务标签= ABC(未售出),因为Inspiron(servicetag = ABC)被出售。因此,在剩余库存中,我应该得到5条记录而不是4条记录。

如何更正此查询?

Select P.Stockno,P.Modelno,P.ServiceTag, Count(P.Stockno) as ClosingBal
From Table_1 as P
Where  P.ServiceTag  Not in (Select ServiceTag from Table_2 )
Group by P.Stockno,P.Modelno,P.ServiceTag

2 个答案:

答案 0 :(得分:0)

SQL FIDDLE DEMO

您的退货结果尚不清楚。因为如果你想要总计,你必须更改组,如果你想显示库存中的项目,那么不需要计数。

Select P.Stockno, P.Modelno, P.ServiceTag, Count(P.Stockno) as ClosingBal
From Table_1 as P
left join Table_2 T
    on P.Stockno = T.Stockno
   and P.ServiceTag = T.ServiceTag
Where  T.ServiceTag IS NULL
Group by P.Stockno, P.Modelno, P.ServiceTag

我在这里使用serviceTagStockNo匹配两个表,因为你没有包含PK / FK

答案 1 :(得分:0)

使用此查询:

select s.* from 
(
    select a.*, case when b.stock_no is null then 'in stock' else 'sold' end [status] 
    from @stock a left join @sales b on a.service_tag = b.service_tag and a.model_no = b.model_no
) s where s.status <> 'sold'

输出:

stock_no    start_dt                service_tag model_no    status
123         2015-08-01 00:00:00.000 JKL         Inspiron    in stock
456         2015-08-01 00:00:00.000 MNO         Galaxy      in stock
456         2015-07-01 00:00:00.000 PQR         Galaxy      in stock
456         2015-08-01 00:00:00.000 VWX         Galaxy      in stock
456         2015-08-01 00:00:00.000 ABC         Galaxy      in stock