2012-03-06 16 views
2

所以這是我table--如何在oracle中使用sys_connect_by_path函數時省略第一個和最後一個逗號?

create table student 
(
stu_id int, 
s_name nvarchar(max), 
s_subject nvarchar(max), 
marks varchar(20) 
) 

和值

insert into student values(123,'pammy','English','88'); 
insert into student values(123,'pammy','Maths','56'); 
insert into student values(124,'watts','Biology','98'); 
insert into student values(125,'Tom','Physics','90'); 
insert into student values(125,'Tom','Computer','95'); 
insert into student values(125,'Tom','ED','75'); 

所以我做了什麼是發生三次提取數據。然後使用sys_connect_by_path連接字符串值。 我的代碼is--我的代碼

select stu_id,s_name, 
max(sys_connect_by_path(s_subject, ', ')) s_subject, 
max(sys_connect_by_path(marks, ', ')) marks 

    from (select stu_id,s_name,s_subject,marks, 
        row_number() over 
        (partition by stu_id order by s_subject) rn 
      from student 
       ) 
    start with rn = 1 
    connect by prior rn = rn-1 and prior stu_id = stu_id 
    group by stu_id,s_name 
having stu_id in (select stu_id 
        from student 
        group by stu_id 
        having count(stu_id) >3) 
    order by stu_id,s_name 

輸出 -

stu_id  s_name s_subject    marks 
125   Tom  ,Physics,Computer,ED, ,90,95,75, 

的代碼工作完美,但我使用逗號作爲seprator,我只是想擺脫逗號在開始和結束時。在s_subject列中。

我想要的東西是

stu_id S_NAME s_subject標記 125個湯姆物理學,計算機,ED 90,95,75

我試圖修正功能,但我不能得到成功。 如果我的數據是固定的,我可以通過路徑來連接sys連接,但是這裏的數據不是固定的。 所以請幫助..

回答

1
SQL> select stu_id 
    2  , s_name 
    3  , ltrim(max(sys_connect_by_path(s_subject, ', ')),', ') s_subject 
    4  , ltrim(max(sys_connect_by_path(marks, ', ')),', ') marks 
    5  from (select stu_id 
    6     , s_name 
    7     , s_subject 
    8     , marks 
    9     , row_number() over (partition by stu_id order by s_subject) rn 
10    from student 
11   ) 
12 where level >= 3 
13 start with rn = 1 
14 connect by prior rn = rn - 1 
15  and prior stu_id = stu_id 
16 group by stu_id 
17  , s_name 
18/

    STU_ID S_NAME  S_SUBJECT      MARKS 
---------- ---------- ------------------------------ -------------------- 
     125 Tom  Computer, ED, Physics   95, 75, 90 

1 row selected. 

問候,
羅布。

PS:感謝和+1提供創建表語句和插入語句。

+0

非常感謝Rob。 – 2012-03-06 14:00:04

0
substr(max(sys_connect_by_path(s_subject, ', ')), 
    2, 
    length(max(sys_connect_by_path(s_subject, ', '))-1) 
2

這是我會怎麼做,在甲骨文11.2:

SQL> select stu_id, s_name, 
    2  listagg(s_subject, ', ') within group (order by s_subject) s_subject, 
    3  listagg(marks, ', ') within group (order by s_subject) marks 
    4 from student 
    5 group by stu_id, s_name; 

STU_ID S_NAME   S_SUBJECT     MARKS 
------ --------------- ------------------------- --------------- 
    123 pammy   English, Maths   88, 56 
    124 watts   Biology     98 
    125 Tom    Computer, ED, Physics  95, 75, 90 

請注意,我按主題排序兩個列表,所以才能在每個列表欄對應。

相關問題