简体   繁体   English

如何按顺序查找最高记录

[英]How do I find highest record in sequence

I need to join two tables using a multipart key, selecting only the records in the second table with the highest sequence numbers (equating to latest version). 我需要使用一个多部分键来连接两个表,仅选择第二个表中具有最高序号(等于最新版本)的记录。 I'm having issues with this. 我对此有疑问。

Table A Key1, Key2, Key3, data1, Data2 表A Key1,Key2,Key3,data1,Data2

Table B Key1, Key2, Key3, Key4, Key5, Key_SEQ, Data1, Data2 表B Key1,Key2,Key3,Key4,Key5,Key_SEQ,Data1,Data2

I need to join the two tables on keya/keyb/kyc and selecting only the max sequence. 我需要加入keya / keyb / kyc上的两个表并仅选择最大序列。 the examples I have seen seem to work for single part keys, but seem unwieldly on multipart keys. 我所看到的示例似乎适用于单部分键,但似乎不适用于多部分键。

Just an update, the database is DB2i (iSeries). 只是更新,数据库是DB2i(iSeries)。

You don't mention which SQL database you are using. 您没有提到要使用哪个SQL数据库。 The following is standard SQL and should perform well in most databases: 以下是标准SQL,在大多数数据库中应表现良好:

select *
from tablea a join
     tableb b
     on a.key1 = b.key1 and
        a.key2 = b.key2 and
        a.key3 = b.key3
where not exists (select 1
                  from tableb b2
                  where b.key1 = b2.key1 and
                        b.key2 = b2.key2 and
                        b.key3 = b2.key3 and
                        b2.key_seq > b.key_seq
                 );

You might be able to do it with a GROUP BY clause, but I'm not entirely sure. 您也许可以使用GROUP BY子句来做到这一点,但我不确定。

SELECT * from A join B on A.key1=B.key1 AND A.key2=B.key2 AND A.key3=B.key3 AND B.Key_SEQ = MAX(B.Key_SEQ) GROUP BY B.key1, B.key2, B.key3;

Another approach is to use a left join syntax: 另一种方法是使用左连接语法:

SELECT A.*, B.* from A join B on A.key1=B.key1 AND A.key2=B.key2 AND A.key3=B.key3 LEFT JOIN B as b2 on B.key1 = b2.key1 AND B.key2 = b2.key2 AND B.key3 = b2.key3 AND B.Key_SEQ < b2.Key_SEQ WHERE b2.Key_SEQ IS NULL;

This query basically says "Give A join B join B again, where the Second B is greater than the First B, but Second B doesn't exist." 该查询基本上说:“再次给A联接B联接B,第二个B大于第一个B,但第二个B不存在。” In other words, there is no B higher than the first B. 换句话说,没有B高于第一个B。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM