在SQL Server 2008中匹配两个表

时间:2015-03-02 09:26:02

标签: sql-server sql-server-2008

我有两张桌子:

  1. Despatch
  2. 激活
  3. Despatch表包含供应商发送的产品数据,DispatchDateLotQty e.t.c

    激活表包含供应商在Despatch表中发送的安装在客户住所的产品数据,即ActivationDateLotQty e.t.c

    在以下查询的帮助下,我设法获得了一些问题的数据,

    select
    (
        select distinct QTY
        from Despatch
        where LOTQty = '1007'
    )as LotQty
    
    ,(
        select COUNT(ProductNumber)
        from Despatch
        where LOTQty = '1007'
    )as ApprovedQty
    
    ,(
        select distinct(DispatchDate)
        from Despatch
        where LOTQty = '1007'
    )as DispatchDate
    
    ,(
        select distinct(ProductModel)
        from Despatch
        where LOTQty = '1007'
    )as Model
    
    ,(
        select COUNT(ProductNumber)
        from Activation
        where LotQty = '1007'
    )as Installed
    

    产生如下结果:
    enter image description here

    但在上面的例子中,它需要整个已安装的数据。我的要求是针对该特定地段中的每个productNumber,它应首先检查发货日期。如果已安装表的激活日期仅大于DispatchDate表的Despatch,那么它应该考虑该条目,否则忽略它。

    编辑:
    我需要的是大致类似的东西

    (   
     select COUNT(ProductNumber)
     from Activation
     where LotQty = '1007'and ActivationDate in Activation for that ProductNumber >   DispatchDate in Despatch for the same ProductName  
    )as Installed
    

    提前致谢。

1 个答案:

答案 0 :(得分:0)

您可以尝试过滤OUTER APPLY表达式中的激活行和按Dispatch表分组:

DECLARE @D TABLE
    (
      LotQty NVARCHAR(50) ,
      ProductNumber NVARCHAR(50) ,
      DispatchDate DATE ,
      ProductModel NVARCHAR(50)
    )
DECLARE @A TABLE
    (
      LotQty NVARCHAR(50) ,
      ProductNumber NVARCHAR(50) ,
      ActivationDate DATE
    )


INSERT  INTO @d
VALUES  ( '1007', 'N1', '20150112', 'ModelA' ),
        ( '1007', 'N2', '20150112', 'ModelA' ),
        ( '1007', 'N3', '20150112', 'ModelA' ),
        ( '1007', 'N4', '20150112', 'ModelA' ),
        ( '1007', 'N5', '20150112', 'ModelA' )

INSERT  INTO @A
VALUES  ( '1007', 'N1', '20150101' ),
        ( '1007', 'N1', '20150102' ),
        ( '1007', 'N2', '20150101' ),
        ( '1007', 'N2', '20150113' ),
        ( '1007', 'N2', '20150114' ),
        ( '1007', 'N3', '20150205' ),
        ( '1007', 'N4', '20150207' ),
        ( '1007', 'N5', '20150101' )

SELECT  d.LotQty ,
        COUNT(d.ProductNumber) AS ProductNumber ,
        MAX(DispatchDate) AS DispatchDate ,
        MAX(ProductModel) AS ProductModel ,
        SUM(o.c) AS Installed
FROM    @D d
        OUTER APPLY ( SELECT    COUNT(*) AS c
                      FROM      @A a
                      WHERE     d.LotQty = a.LotQty
                                AND d.ProductNumber = a.ProductNumber
                                AND a.ActivationDate > d.DispatchDate
                      GROUP BY  a.LotQty ,
                                a.ProductNumber
                    ) AS o
WHERE   d.LotQty = '1007'
GROUP BY d.LotQty

输出:

LotQty  ApprovedQty     DispatchDate    ProductModel    Installed
1007    5               2015-02-15      ModelA          4