我有两个表,在第一个表中存储了课程ID,在第二个表中,课程ID和不同的主题区域描述存储如下所示。
Table PA_CPNT
CPNT_ID( Course ID) Course Title
06201826 AAAA
06201827 BBBB
06201828 CCCC
Table PA_CPNT_SUBJ
CPNT_ID SUBJ_ID
06201826 PLNT_DEV
06201826 WRKS_COUN
06201827 WRKS_COUN1
06201827 WRKS_COUN2
06201827 WRKS_COUN3
06201828 WRKS_COUN
My requirement is to have an output in the below format
CPNT_ID COUrse Title SUBJ_ID1 SUBJ_ID2 SUBJ_ID3
06201826 AAAA PLNT_DEV WRKS_COUN
06201827 BBBB WRKS_COUN1 WRKS_COUN2 WRKS_COUN3
06201828 CCCC WRKS_COUN
我编写了以下代码,如何修改此代码以达到上述要求。
select distinct CPNT_ID,
cpnt_desc,
SUBJ_ID1,
SUBJ_ID2,
SUBJ_ID3
from
(
select a.cpnt_id,
a.cpnt_desc,
b.subj_id as subj_id1,
c.subj_id as subj_id2,
d.subj_id as subj_id3
from PA_CPNT a
inner join PA_CPNT_SUBJ b
on a.cpnt_id=b.cpnt_id
inner join PA_CPNT_SUBJ c
on a.cpnt_id=c.cpnt_id
inner join PA_CPNT_SUBJ d
on a.cpnt_id=d.cpnt_id
) X
where subj_id1 ! = subj_id2
and subj_id2 ! = subj_id3
and subj_id3 ! = subj_id1
请帮忙
答案 0 :(得分:1)
select DISTINCT
a.cpnt_id,
a.cpnt_desc,
b.subj_id as subj_id1,
c.subj_id as subj_id2,
d.subj_id as subj_id3
from PA_CPNT a
left join PA_CPNT_SUBJ b
on a.cpnt_id=b.cpnt_id
left join PA_CPNT_SUBJ c
on a.cpnt_id=c.cpnt_id and b.subj_id < c.subj_id
left join PA_CPNT_SUBJ d
on a.cpnt_id=d.cpnt_id and c.subj_id < d.subj_id
使用<
而不是!=
可以防止它生成包含主题所有不同排列的重复项。
答案 1 :(得分:0)
您可以使用此查询...
select a.cpnt_id,
a.cpnt_desc,
b.subj_id as subj_id1,
c.subj_id as subj_id2,
d.subj_id as subj_id3
from PA_CPNT a
left join PA_CPNT_SUBJ b on a.cpnt_id=b.cpnt_id and b.subj_id='PLNT_DEV'
left join PA_CPNT_SUBJ c on a.cpnt_id=c.cpnt_id and c.subj_id='WRKS_COUN'
left join PA_CPNT_SUBJ d on a.cpnt_id=d.cpnt_id and d.subj_id='WRKS_COUN1'
答案 2 :(得分:0)
不需要多次连接表pa_cpnt_subj。
您可以按cpnt_id分组。第一个值当然是最小的subj_id,第二个(如果有一个以上的主题)可以计算(假设从不超过三个值,我们可以用having子句保证),最后一个(以防万一)有超过2个科目)是最大的subj_id。
select
pa_cpnt.cpnt_id,
pa_cpnt.cpnt_desc,
min(pa_cpnt_subj.subj_id) as subj_id1,
case when count(*) > 1 then
avg(pa_cpnt_subj.subj_id) * count(*)
- min(pa_cpnt_subj.subj_id)
- max(pa_cpnt_subj.subj_id)
end as subj_id2,
case when count(*) > 2 then
max(pa_cpnt_subj.subj_id)
end as subj_id3
from pa_cpnt
left outer join pa_cpnt_subj on pa_cpnt_subj.cpnt_id = pa_cpnt.cpnt_id
group by pa_cpnt.cpnt_id, pa_cpnt.cpnt_desc
having count(*) <= 3;
答案 3 :(得分:0)
您可以使用row_number为课程中的每个科目提供一个数字,然后显示科目#1,#2和#3。
select
pa_cpnt.cpnt_id,
pa_cpnt.cpnt_desc,
min(case when subj.rn = 1 then subj.subj_id end) as subj_id1,
min(case when subj.rn = 2 then subj.subj_id end) as subj_id2,
min(case when subj.rn = 3 then subj.subj_id end) as subj_id3
from pa_cpnt
left outer join
(
select
cpnt_id,
subj_id,
row_number() over (partition by cpnt_id order by subj_id) as rn
from pa_cpnt_subj
) subj on subj.cpnt_id = pa_cpnt.cpnt_id
group by pa_cpnt.cpnt_id, pa_cpnt.cpnt_desc;