专家给出的答案:
--> 测试数据: #ta
if
object_id('tempdb.dbo.#ta') is
not
null
drop
table #ta
go
create
table #ta (出库单号 int,日期 datetime,客户 varchar(1))
insert
into #ta
select
1,'2010-10-11','A'
union
all
select
2,'2010-12-11','A'
union
all
select
3,'2010-10-11','B'
--> 测试数据: #tb
if
object_id('tempdb.dbo.#tb') is
not
null
drop
table #tb
go
create
table #tb (出库单号 int,产品 varchar(2),数量 int)
insert
into #tb
select
1,'一',10
union
all
select
1,'二',10
union
all
select
2,'一',10
union
all
select
3,'一',10
union
all
select
3,'二',10
;with cte as
(
select a.出库单号, 客户, 产品, 最后订购日期= 日期 ,订购数量=数量
from #ta a , #tb b
where a.出库单号=b.出库单号
)
select
*
from cte t
where
not
exists(select
1
from cte where 客户=t.客户 and 产品=t.产品 and 最后订购日期>t.最后订购日期)
出库单号 客户 产品 最后订购日期 订购数量
----------- ---- ---- ----------------------- -----------
1 A 二 2010-10-11
00:00:00.000
10
2 A 一 2010-12-11
00:00:00.000
10
3 B 一 2010-10-11
00:00:00.000
10
3 B 二 2010-10-11
00:00:00.000
10
(4 行受影响)