1

我有下表

    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

编辑:我现在正在尝试以下查询:

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

伙计们请帮助我获得我想要的输出。

4

1 回答 1

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 字符串聚合技术之一。在 11.2 之前,我个人的偏好是创建一个用户定义的聚合函数,这样你就可以

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

但是,如果您不想创建函数,则可以使用ROW_NUMBER 和 SYS_CONNECT_BY_PATH 方法,尽管这往往会有点难以遵循

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
于 2012-02-28T15:22:54.983 回答