简体   繁体   English

DB2过滤行并从字符串排序中获取最新条目

[英]DB2 Filter rows and get latest entry from string sort

I have the following table: 我有下表:

Table A 表A

 Nr | Key | String 
 1     1      test
 1     1      zert
 2     3      teuz
 2     4      asf
 3     5      hgf
 3     5      zzzz

And I want the result table to be like: 我希望结果表像这样:

Nr  | key | String
1..    1     zert
2      3     teuz
2      4     asf
3..    5     zzzz

Explain: If Nr and key are the same I need to get .. attached to the Nr and only the latest String value. 说明:如果Nr和key相同,我需要将..附加到Nr上,并且仅附加最新的String值。 If the match of Nr and key is unique I just need that row as is in the table. 如果Nr和key的匹配是唯一的,我只需要表中的那一行。

From a similar problem I started to work with this: 从类似的问题开始,我开始对此进行处理:

 with tmp as (
    select i.nr, i.key as nt, count(*) as cnt
    from a
    group by i.nr, i.key)
 select case
     when tmp.cnt = 1 then char(a.nr)
     else concat(rtrim(char(a.nr)), '..')
   end as nr,
   a.key, 
   a.string
from tmp
  left outer join a 
       on a.nr = tmp.nr
       and a.key = tmp.key
order by nr asc

What I get right now is: 我现在得到的是:

 Nr | key | String
 1..   1      test
 1..   1      zert
 2     3      teuz
 2     4      asf
 3..   5      hgf
 3..   5      zzzz

It does not leave out the the older rows. 它不会忽略较旧的行。

System: Windows DB2 v. 10.5 系统:Windows DB2 v。10.5

Thank you for all your help. 谢谢你的帮助。

Viking 维京人

with tmp as(
  select a.nr nr, 
         a.key as key, 
         max(a.string) as string,  
         count(*) as cnt 
    from table a 
    group by a.nr, a.key 
  )
select distinct
       tmp.nr as nr,
       tmp.key as key,
       case
         when tmp.cnt = 1 then trim(tmp.string)
         else concat(char(trim(tmp.string)), '..')
       end as string
  from table a    
    join tmp 
      on a.nr = tmp.nr 
       and a.key = tmp.key 
  order by nr, string asc;

try this: 尝试这个:

with tmp as (
select f0.Nr OldNr, f0.Key, rownumber() over(partition by f0.Nr order by rrn(f0) desc) rang,
case when f0.Nr=f0.Key then cast(f0.Nr || '..' as varchar(20)) else cast(f0.Nr as varchar(20)) end Nr
from tableA f0
)
select distinct f2.Nr, f2.Key 
case when f2.OldNr=f2.Key then f2.String else f1.String end as String 
from tableA f1 
inner join tmp f2 on f1.Nr=f2.OldNr and f2.rang=1 

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

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