在INNER JOIN之后从两个表中获取MAX日期

时间:2016-09-01 16:57:10

标签: sql sql-server greatest-n-per-group

我有以下表格:

declare @tbl1 table (Id1 int, crtdate datetime, InvcNbr varchar(10), ShipperId varchar(10), InvtId varchar(10))
insert into @tbl1 values (1,'01/01/2016','001','S111','111')
insert into @tbl1 values (2,'01/10/2016','002','S111','111')
insert into @tbl1 values (3,'01/02/2016','003','S112','112')
insert into @tbl1 values (4,'01/08/2016','004','S112','112')
insert into @tbl1 values (5,'01/04/2016','005','S113','113')
insert into @tbl1 values (6,'01/05/2016','006','S114','113')

declare @tbl2 table (Id2 int, SerialNo varchar(10), InvcNbr varchar(10), ShipperId varchar(10), InvtId varchar(10))
insert into @tbl2 values (1,'1111111','001','S111','111')
insert into @tbl2 values (2,'1111111','002','S111','111')
insert into @tbl2 values (3,'1111112','003','S112','112')
insert into @tbl2 values (4,'1111112','004','S112','112')
insert into @tbl2 values (5,'1111113','005','S113','113')
insert into @tbl2 values (6,'1111113','006','S114','113')

这两个表与字段相关:InvcNbr, ShipperId and InvtId

来自@tbl2的序列出现在两张不同的发票中(InvcNbr)。如何仅显示最新InvcNbr

的结果

结果应该是这样的:

Id1 crtdate                 InvcNbr ShipperId   InvtId  Id2 SerialNo    InvcNbr ShipperId   InvtId
2   2016-01-10 00:00:00.000 002     S111        111     2   1111111     002     S111        111
4   2016-01-08 00:00:00.000 004     S112        112     4   1111112     004     S112        112
6   2016-01-05 00:00:00.000 006     S114        113     6   1111113     006     S114        113

2 个答案:

答案 0 :(得分:1)

with lastInvoices as (
        select SerialNo, MAX(InvcNbr) LastInvcNbr
        from @tbl2
        group by SerialNo
    )
select t1.*,t2.*
from lastInvoices li
    join @tbl2 t2 on (li.SerialNo = t2.SerialNo and li.LastInvcNbr=t2.InvcNbr)
    join @tbl1 t1 on (t1.InvcNbr = t2.InvcNbr and t1.ShipperId = t2.ShipperId and t1.InvtId = t2.InvtId)

答案 1 :(得分:0)

下面的脚本将为您提供所需的结果..

id