列中的列值

时间:2012-02-28 13:12:37

标签: string oracle11g oracle11gr1

我有下表

    id    count   hour   age   range
    -------------------------------------
    0       5       10     61     10-200
    1       6       20     61     10-200
    2       7       15     61     10-200  
    5       9       5      61     201-300
    7       10      25     61     201-300
    0       5       10     62     10-20
    1       6       20     62     10-20
    2       7       15     62     10-20  
    5       9       5      62     21-30
    1       8       6      62     21-30
    7       10      25     62     21-30
    10      15      30     62     31-40

我需要选择列范围的不同值 我尝试了以下查询

Select distinct range as interval from table name where age  = 62;

其结果如下所示:

interval
----------
10-20
21-30
31-41

我如何得到如下结果?

10-20, 21-30, 31-40

EDITED: 我现在正在尝试以下查询:

select sys_connect_by_path(range,',') interval
from
    (select distinct NVL(range,'0') range , ROW_NUMBER() OVER (ORDER BY RANGE) rn 

 from table_name where age = 62)

 where connect_by_isleaf = 1 CONNECT BY rn = PRIOR rn+1 start with rn = 1;

这给了我输出:

Interval
----------------------------------------------------------------------------
, 10-20,10-20,10-20,21-30,21-30, 31-40
伙计们帮助我得到我想要的输出。

1 个答案:

答案 0 :(得分:2)

如果您使用的是11.2而不是11.1,则可以使用LISTAGG聚合函数

SELECT listagg( interval, ',' ) 
         WITHIN GROUP( ORDER BY interval )
  FROM (SELECT DISTINCT range AS interval
          FROM table_name
         WHERE age = 62)

如果您使用的是早期版本的Oracle,则可以使用Tim Hall页面上的其他Oracle string aggregation techniques之一。在11.2之前,我个人的偏好是创建user-defined aggregate function,以便您可以

SELECT string_agg( interval )
  FROM (SELECT DISTINCT range AS interval
              FROM table_name
             WHERE age = 62)

但是,如果你不想创建一个函数,你可以使用ROW_NUMBER and SYS_CONNECT_BY_PATH approach,但这往往会更难以理解

with x as (
  SELECT DISTINCT range AS interval
          FROM table_name
         WHERE age = 62 )
select ltrim( max( sys_connect_by_path(interval, ','))
                keep (dense_rank last order by curr),
              ',') range
  from (select interval,
               row_number() over (order by interval) as curr,
               row_number() over (order by interval) -1 as prev
          from x)
connect by prev = PRIOR curr
  start with curr = 1