代码之家  ›  专栏  ›  技术社区  ›  Ian Carpenter

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

  •  7
  • Ian Carpenter  · 技术社区  · 14 年前

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

    表t1(主键同时显示两列)

    ID    TYPE
    1     A
    1     B
    1     C
    
    2     A
    2     B
    
    3     B
    

    表t2(主键为类型)

    Type    Desc
    A       xx
    
    B       xx
    
    C       xx
    

    所以考虑到T1中的数据,我需要的结果是:

    对于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')
    /
    
    1 回复  |  直到 14 年前
        1
  •  5
  •   Craig    14 年前

    像这样的东西会让你得到你想要的:

    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的问题!