我有两张桌子:
Despatch
表包含供应商发送的产品数据,DispatchDate
,LotQty
e.t.c
激活表包含供应商在Despatch
表中发送的安装在客户住所的产品数据,即ActivationDate
,LotQty
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
产生如下结果:
但在上面的例子中,它需要整个已安装的数据。我的要求是针对该特定地段中的每个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
提前致谢。
答案 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