我有一个如下所示的表:
COL1 COL2 KEY1 KEY2 VERSION
1 11 ABC 0 0
2 12 ABC 1 0
1 11 ABC 0 0
2 13 ABC 1 1
我想得到";最新的";行使用基于key1和key2的组合键,并且仅在version
已更改时选择最新版本。因此,在这种情况下,我希望获得单行的输出,因为这是唯一一个版本在这个复合密钥中递增的行:
COL1 COL2 KEY1 KEY2 VERSION
2 13 ABC 1 1
我有一个查询,看起来像这样,它根据版本给了我最新的一行,但不考虑版本更改:
select col1, col2
from
select col1,
col2,
concat(key1, key2) as composite_key,
row_number() over (partition BY(key1, key2) order by version desc) rank
from partitions
) updates
where updates.rank = 1
COL1 COL2
1 11
2 13
我需要添加哪些内容来说明版本?我假设一个小组在某个时候通过,但在这种情况下,我很难获得col1
和col2
。
我想你只需要lag()
:
select col1, col2
from (select p.*,
lag(version) over (partition by key, key order by version) as prev_version
row_number() over (partition by key1, key2 order by version desc) as seqnum
from partitions p
) p
where p.seqnum = 1 and p.prev_version <> p.version;