现有表 
A:
taid 
1
2
3
...B:
tbid taid seq_no code
1    1     1     AAA  
2    1     2     BBB
3    1     3     CCC
4    2     1     XXX
5    2     2     YYYB.taid reference A.taid
如何通过sql语句得到 试图C
taid codestr
1    AAA-BBB-CCC
2    XXX-YYY
谢谢!

解决方案 »

  1.   

    select a.taid,replace(wm_concat(b.code),',','-')codestr
    from a,b
    where a.taid=b.taid
    group by a.taid
      

  2.   

    9i的select taid,substr(max(sys_connect_by_path(code,'-')),2)codestr
    from(
      select a.taid,b.code,
        row_number()over(partition by a.taid order by b.tbid)rn
      from a,b
      where a.taid=b.taid)
    connect by prior taid=taid and prior rn=rn-1
    start with rn=1
    group by taid
      

  3.   

    行列转换吧!
    -----------------------------------------------------
    10g: select get_request_line_no,  wagon_no, wmsys.wm_concat(storage_no) 
      from you_tab 
    group by get_request_line_no,  wagon_no 
    --------------------------------------------------------------------
    9i可用自定义聚集函数create table t2(col1 varchar2(10),col2 varchar2(10)); 
    insert into t2 values('001','vl1'); 
    insert into t2 values('001','vl2'); 
    insert into t2 values('001','vl3'); 
    insert into t2 values('002','vl1'); 
    insert into t2 values('002','vl2'); SELECT COL1, LTRIM(MAX(SYS_CONNECT_BY_PATH(COL2, ',')), ',') COL2 
    FROM (SELECT COL1, 
                   COL2, 
                   MIN(COL2) OVER(PARTITION BY COL1) COL2_MIN, 
                   (ROW_NUMBER() OVER(ORDER BY COL1, COL2)) + 
                   (DENSE_RANK() OVER(ORDER BY COL1)) NUMID 
              FROM T2) 
    START WITH COL2 = COL2_MIN 
    CONNECT BY NUMID - 1 = PRIOR NUMID 
    GROUP BY COL1 --------------------------------------------------
    /*
    COL1       COL2                                    
    ---------- ----------------------------------------
    001        vl1,vl2,vl3                             
    002        vl1,vl2                                 
    2 rows selected
    */
      

  4.   


    B: 
    tbid taid seq_no code 
    1    1    1    CAN  
    2    1    2    SYM 
    3    1    3    PEK 
    4    2    1    XXX 
    5    2    2    YYY
    时,应该对应 1 CAN-SYM-PEK
    但结果为    1 CAN-PEK-SYM 
    如何按 seq_no排序?
      

  5.   

    要按seq_no排序的话试试在wm_concat前进行下排序select taid,replace(wm_concat(code),',','-')codestr 
      (select a.taid,b.code
       from a,b 
       where a.taid=b.taid 
       order by b.tbid)
    group by taid
    看看顺序是否变过来了。不过这样对数据量大的表会有性能上的问题
    可以用2楼的connect by试试
    如果需要可以将partition by a.taid order by b.tbid换成partition by a.taid order by b.seq_no
      

  6.   

    我觉得应该用上seq_no
    给出以下答案:
    select t.taid,replace(wm_concat(code),',','-') from (
    select taid,code from B group by taid,code,seq_no order by taid,seq_no) t ,A a 
    where a.taid = t.taid group by t.taid