2010-11-10 21 views
7

我已经使用PL/SQL和SQL编写了问题的解决方案,我不禁想到它可以在SQL中完成100%,但是我正在努力开始。PL/SQL中解决的问题在SQL中它看起来像什么?

这里是两个表的结构(如果有帮助,这些脚本创建它们是在问题的末尾)

表T1(主键是显示两列)

ID TYPE 
1  A 
1  B 
1  C 

2  A 
2  B 

3  B 

类型列是一个外键表T2,其包含以下数据:

表T2(主键是类型)

Type Desc 
A  xx 

B  xx 

C  xx 

所以给出的数据在T1的结果,我需要的是:

对于ID 1,因为它具有外键的表我将返回文本“全部”

对于ID 2的所有类型因为它有两种类型,我想回到“A & B”(注意分隔符)

终于为ID 3,因为它有一个类型的,我想只返回“B”

如这里承诺是创建所有提到的对象的脚本。

create table t2(type varchar2(1), 
       description varchar2(100) 
       )     
/

insert into t2 
values ('A', 'xx') 
/

insert into t2 
values ('B', 'xx') 
/

insert into t2 
values ('C', 'xx') 
/

alter table t2 add constraint t2_pk primary key (type) 
/

create table t1 (id number(10), 
       type varchar2(1) 
       ) 
/

alter table t1 add constraint t1_pk primary key(id, type) 
/

alter table t1 add constraint t1_fk foreign key (type) 
references t2(type) 
/

insert into t1 
values (1, 'A') 
/

insert into t1 
values (1, 'B') 
/

insert into t1 
values (1, 'C') 
/

insert into t1 
values (2, 'A') 
/

insert into t1 
values (2, 'B') 
/

insert into t1 
values (3, 'B') 
/
+0

你打算在t2中增加更多的类型吗?不只是A,B和C? – mcpeterson 2010-11-10 20:28:23

+0

@mcpeterson:感谢您的评论。 t2中的数据将固定,总共大约5行 – 2010-11-10 21:03:17

+1

面向组的字符串串联需求否定了在纯SQL中执行此操作的能力。 – 2010-11-11 00:18:12

回答

5

像这样的东西应该得到你在找什么:

select 
    id, 
    case 
     when cnt = (select count(distinct type) from t2) 
     then 'All' 
     else ltrim(sys_connect_by_path(type,' & '),' &') 
    end types 
from (
    select 
     t1.id, 
     t2.type, 
     count(*) over (partition by t1.id) cnt, 
     row_number() over (partition by t1.id order by t2.type) rn 
    from 
     t1 
     inner join t2 
      on t2.type = t1.type 
) 
where 
    rn = cnt 
    start with rn = 1 
    connect by prior id = id and prior rn = rn-1; 

我会给你的问题+10,如果我能为您的发布对象/数据创建脚本!

+1

“GROUP BY类型”和聚合函数而不是sys_connect_by_path是否足够? – 2010-11-10 20:37:25

+3

是的,如果你制作一个自定义的聚合函数,你也可以得到相同的解决方案,你也可以用一个组来调用(类似于很常见的stragg函数)。当然,这不是“只是SQL”了,但... – Craig 2010-11-10 22:12:27

+3

如果你有11g,你可以使用LISTAGG分析功能:http://download.oracle.com/docs/cd/E11882_01/server.112 /e17118/functions089.htm – 2010-11-11 04:23:29

相关问题