加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

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

发布时间:2020-12-12 07:26:24 所属栏目:MsSql教程 来源:网络整理
导读:我已经使用PL / SQL和SQL编写了一个问题解决方案,我不禁想到它可以在SQL中100%完成,但我正在努力开始. 这是两个表的结构(如果有帮助,创建它们的脚本就在问题的最后) 表t1(主键是显示的两列) ID TYPE1 A1 B1 C2 A2 B3 B Type列是表T2的外键,其中包含以下数据
我已经使用PL / SQL和SQL编写了一个问题解决方案,我不禁想到它可以在SQL中100%完成,但我正在努力开始.

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

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

ID    TYPE
1     A
1     B
1     C

2     A
2     B

3     B

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

表t2(主键是Type)

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

解决方法

这样的东西可以让你得到你想要的东西:
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!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读