获取具有相同id值的最长字符串的字段

时间:2012-09-11 02:52:43

标签: sql oracle

我必须为相同的id字段获取具有最长字符串值的行。

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;

我想要的输出是


1 abxw - 最新字符串

2 tris

如何获得所需的输出?我不知道。

伙计们如何使用游标。我们可以将光标用于此目的吗?有谁有想法吗?有可能吗?

谢谢。

3 个答案:

答案 0 :(得分:8)

我喜欢使用分区进行这类查询:

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

当然,关于这一点的好处在于,如果您决定要另一个抢七(例如,按字母顺序排列),则只需将其添加到order by子句中。顺便说一句,这不是一个坏主意,那样你的结果集就不会是非确定性的。

答案 1 :(得分:2)

您可以尝试此查询。如果多个字符串的每个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

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

答案 2 :(得分:2)

我认为分析(窗口)函数RANK()是实现此目的的最佳方法。

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

如果您只想要一条记录,那么您可以执行以下操作:

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