2011-03-08 36 views
2

是否可以構建SQL以連接多行的列值?Oracle 10g多列字符串並置

下面是一個例子:

表的SQL的

 
PID 
A 
B 
C 

表B

 
PID SEQ Desc 

A  1  Have 
A  2  a nice 
A  3  day. 
B  1  Nice Work. 
C  1  Yes 
C  2  we can 
C  3  do 
C  4  this work! 

輸出應該是 -

 
PID Desc 

A  day.||a nice||Have 
B  Nice Work. 
C  this work!||do||we can||Yes 

所以基本上說明列出put table是來自表B的SEQ值的串聯,並且這些值以SEQ的降序附加,並且由||來分隔。 ?

SQL的任何幫助?

僅供參考 - 尋找解決方案,而無需使用功能或存儲過程

+0

http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:2196162600402#18313422264397 – 2011-03-08 04:14:20

+0

該示例使用函數! – jagamot 2011-03-08 04:20:40

回答

1

分級查詢應該可以工作。由於你想從每個PID的最高SEQ開始,所以需要一些額外的技巧。

SELECT pid, fulldesc FROM (
    SELECT pid, SYS_CONNECT_BY_PATH(desc, '||') fulldesc, seq, minseq FROM (
    SELECT pid, seq, desc, 
      MAX(seq) OVER (PARTITION BY pid) maxseq, 
      MIN(seq) OVER (PARTITION BY pid) minseq 
     FROM tableB 
    ) 
    START WITH seq = maxseq 
    CONNECT BY pid = PRIOR pid AND seq = PRIOR seq - 1 
) 
    WHERE seq = minseq 
    ORDER BY pid 
    ; 

編輯:添加一個過濾器一種方式的要求,在註釋:

SELECT pid, fulldesc FROM (
    SELECT pid, SYS_CONNECT_BY_PATH(desc, '||') fulldesc, seq, minseq FROM (
    SELECT pid, seq, desc, 
      MAX(seq) OVER (PARTITION BY pid) maxseq, 
      MIN(seq) OVER (PARTITION BY pid) minseq 
     FROM tableB 
     WHERE pid IN (SELECT pid FROM tableB WHERE desc='day.') 
    ) 
    START WITH seq = maxseq 
    CONNECT BY pid = PRIOR pid AND seq = PRIOR seq - 1 
) 
    WHERE seq = minseq 
    ORDER BY pid 
+0

給出 - ORA-00904:「desc」:無效標識符 – jagamot 2011-03-08 14:40:02

+1

對不起,在最內層的查詢中忘記了包含'desc'。固定。 – 2011-03-08 14:41:35

+0

我可以問另外一個問題嗎?[我想添加一個過濾器] - 我想只包含那些包含desc的seq列爲「day」的那些pid。只要。我在哪裏添加where子句? – jagamot 2011-03-08 14:50:45

2

here

但是我有一個函數任何一天去。

SQL> select deptno 
    2  , rtrim(ename,',') enames 
    3 from (select deptno 
    4    , ename 
    5    , rn 
    6    from emp 
    7   model 
    8     partition by (deptno) 
    9     dimension by (row_number() over 
10        (partition by deptno order by ename) rn 
11        ) 
12     measures  (cast(ename as varchar2(40)) ename) 
13     rules 
14     (ename[any] order by rn desc = ename[cv()]||','||ename[cv()+1] 
15     ) 
16  ) 
17 where rn = 1 
18 order by deptno 
19/

    DEPTNO ENAMES 
---------- ---------------------------------------- 
     10 CLARK,KING,MILLER 
     20 ADAMS,FORD,JONES,SCOTT,SMITH 
     30 ALLEN,BLAKE,JAMES,MARTIN,TURNER,WARD 
+0

拋出ORA-00900:關鍵字[any]上的無效SQL語句! – jagamot 2011-03-08 12:26:56