在PL/SQL中完成问题的解决方案在SQL中会是什么样子?

Ian*_*ter 7 sql oracle oracle10g

我已经使用PL/SQL和SQL编写了一个问题解决方案,我不禁想到它可以在SQL中100%完成,但我正在努力开始.

这是两个表的结构(如果有帮助,创建它们的脚本就在问题的最后)

表t1(主键是显示的两列)

ID    TYPE
1     A
1     B
1     C

2     A
2     B

3     B
Run Code Online (Sandbox Code Playgroud)

Type列是表T2的外键,其中包含以下数据:

表t2(主键是Type)

Type    Desc
A       xx

B       xx

C       xx
Run Code Online (Sandbox Code Playgroud)

因此,鉴于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')
/
Run Code Online (Sandbox Code Playgroud)

Cra*_*aig 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;
Run Code Online (Sandbox Code Playgroud)

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

  • 是的,如果您创建一个自定义聚合函数,您可以获得相同的解决方案,您也可以使用组调用(类似于非常常见的stragg函数).当然,这不仅仅是"SQL"了...... :) (3认同)
  • 如果您有11g,则可以使用LISTAGG分析功能:http://download.oracle.com/docs/cd/E11882_01/server.112/e17118/functions089.htm (3认同)