开发者

Solution to problem done in PL/SQL what would it look like in SQL?

I've written a solution to problem using PL/SQL and SQL and I开发者_如何转开发 can't help thinking that it could be done 100% in SQL but am I am struggling to get started.

Here is the structure of the two tables (If it helps, the scripts to create them are at the end of the question)

Table t1 (primary key is both columns displayed)

ID    TYPE
1     A
1     B
1     C

2     A
2     B

3     B

The Type column is a Foreign Key to table T2 which contains the following data:

Table t2 (primary key is Type)

Type    Desc
A       xx

B       xx

C       xx

So given the the data in T1 the result I need will be:

For ID 1 because it has all the types in the foreign key table I would return the literal "All"

For ID 2 because it has two types I would like to return "A & B" (note the separator)

And finally for ID 3 because it has one type I would like to return just "B"

As promised here are the scripts to create all the objects mentioned.

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')
/


Something like this should get you what you are looking for:

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;

I would give your question +10 if I could for posting your object / data creation script!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜