简体   繁体   中英

get the field with longest string for same id value

I have to get the row with longest string value for same id fields.

create table test(
id number,
test_data varchar2(20)
);

insert all      
    into test values (1,'aaa')
    into test values (1,'a')
    into test values (1,'abxw')
    into test values (2,'aaa')
    into test values (2,'tris')
select * from dual;

my desired output is


1 abxw --longest string

2 tris

how can I get the required output?? I am not getting any idea.

guys what about using cursor. can we use cursor for this purpose?? Does anyone have any idea? Is it possible??

Thank You.

I like using partition for these kind of queries:

select id,test_data from (
  select
  id, test_data, 
     row_number() over( partition by id order by length(test_data) desc) as rnum
from
  test 
) where rnum=1

http://www.sqlfiddle.com/#!4/66d4c/20

Of course, the nice thing about this is that if you decide that you want another tiebreak (eg, alphabetically), you just need to add that to your order by clause. Which, by the way is not a bad idea, that way your result set will not be non-deterministic.

You can try this query. It will return multiple results if multiple strings have the longest length per id:

select
  t1.id, t1.test_data
from
  test t1
join
  (select id, max(length(test_data)) as len from test group by id) t2
    on t1.id = t2.id and length(t1.test_data) = t2.len

Demo: http://www.sqlfiddle.com/#!4/66d4c/6

I think the analytic (window) function RANK() is the best way to accomplish this.

SELECT id, test_data FROM (
    SELECT id, test_data
         , RANK() OVER ( PARTITION BY id ORDER BY LENGTH(test_data) DESC ) AS the_rank
      FROM test
) WHERE the_rank = 1

If you want only one record, then you can do the following:

SELECT id, test_data FROM (
    SELECT id, test_data
         , RANK() OVER ( PARTITION BY id ORDER BY LENGTH(test_data) DESC ) AS the_rank
      FROM test
     ORDER BY the_rank
) WHERE rownum = 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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