2012-02-28 57 views
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; 

這是給我的輸出:

傢伙plz幫助我,讓我所需的輸出。

回答

2

如果你是在11.2,而不是僅僅11.1,你可以,如果你使用的是Oracle的早期版本使用LISTAGG聚合函數

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

,您可以使用其他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 
+0

沒有即時通訊使用11.1其不支持listagg和連接函數。 – Pramod 2012-02-29 05:49:10

+0

@Pramod - 更新了我的回答11.2以前的功能 – 2012-02-29 09:18:22

+0

謝謝賈斯汀它真的有效..非常感謝你 – Pramod 2012-02-29 09:24:56