日期:2014-05-17  浏览次数:20823 次

请教一查询语句写法
表结构:
create   table   TBL_TEST   (TID   VARCHAR2(2),   NM     VARCHAR2(2))
表数据:
insert   into   TBL_TEST2   (TID,   NM)   values   ( '1 ',   'a ');
insert   into   TBL_TEST2   (TID,   NM)   values   ( '2 ',   'b ');
insert   into   TBL_TEST2   (TID,   NM)   values   ( '3 ',   'c ');
insert   into   TBL_TEST2   (TID,   NM)   values   ( '1 ',   'd ');
即为:
TID NM
1 a
2 b
3 c
1 d
----------------------
现在想要得出下面的集合该怎么写:
TID NM
1 ad
2 b
3 c
----------------------
即:按TID分类,如果TID一样则num列字符串并在一起(不是sum)
注:TID、NM中的值是不固定的
我想了半天想不出来,只好找大家帮忙了

------解决方案--------------------
CREATE OR REPLACE function link(v_id varchar2)
return varchar2
is
union_nm varchar2(200);
begin
for cur in (select nm from TBL_TEST where tid=v_id) loop
union_nm := union_nm||cur.nm;
end loop;
union_nm := rtrim(union_nm,1);
return union_nm;
end;
///
select tid,link(tid) from tbl_test group by tid
------解决方案--------------------
select tid, replace(max(sys_connect_by_path(nm, ', ')), ', ', ' ') from
(SELECT tid, nm, MIN(nm) over(PARTITION BY tid) minnm
,(row_number() over(ORDER BY tid, nm)) + (dense_rank() over(ORDER BY tid)) no
FROM ttt)
start with nm=minnm
connect by no-1 = prior no
group by tid
------解决方案--------------------
使用这个sys_connect_by_path就可以了
------解决方案--------------------
具体范例参照:
http://hitc.blogdriver.com/hitc/465373.html