我是sql的新手,我正在尝试执行以下操作:
我的查询目前根据where子句拉回两个字段:
select distinct
count(distinct t1.p_id) "c1",
count(distinct t2.sa_id) "c2"
from capd_section t5,
capd_department t6,
capd_person t1,
capd_studentapplication t2,
capd_module t4,
capd_moduleapplication t3
where (t3.ma_studentapplication(+)=t2.sa_id) and
(t3.ma_module=t4.m_id(+)) and
(t4.m_modulesection=t5.s_id(+)) and
(t4.m_moduledept=t6.d_id(+)) and
(t4.m_reference not like '%%FTA%%') and
**(t2.sa_reference like '212%%')** and
(t4.m_reference not like '%%HE%%') and
(t4.m_reference not like '%%PT%%') and
(t4.m_name not like 'NCTJ%%') and
(t4.m_reference not like 'ME%%') and
(t2.sa_student=t1.p_id)
having (count(distinct t3.ma_id)>0)
我希望拥有相同的查询但是使用where子句(t2.sa_reference,如'213 %%')来撤回。 (当前年份和上一年度)
总共四个字段(c1,c2,c3,c4)。如果这有任何意义的话。它甚至可能吗?
非常感谢任何帮助:)答案 0 :(得分:1)
您只需添加或声明以检查第二个值,然后尝试查询:
select distinct
count(distinct t1.p_id) "c1",
count(distinct t2.sa_id) "c2"
from capd_section t5,
capd_department t6,
capd_person t1,
capd_studentapplication t2,
capd_module t4,
capd_moduleapplication t3
where (t3.ma_studentapplication(+)=t2.sa_id) and
(t3.ma_module=t4.m_id(+)) and
(t4.m_modulesection=t5.s_id(+)) and
(t4.m_moduledept=t6.d_id(+)) and
(t4.m_reference not like '%%FTA%%') and
((t2.sa_reference like '212%%')or (t2.sa_reference like '213%%')) and
(t4.m_reference not like '%%HE%%') and
(t4.m_reference not like '%%PT%%') and
(t4.m_name not like 'NCTJ%%') and
(t4.m_reference not like 'ME%%') and
(t2.sa_student=t1.p_id)
having (count(distinct t3.ma_id)>0);
这里我修改了你的条件,通过使用((t2.sa_reference like '212%%')or (t2.sa_reference like '213%%'))
这个子句来检查这两个值。因此,如果其中任何一个得到满足,您可以检索行。
答案 1 :(得分:0)
只需在COUNT语句中使用CASE:
select distinct
count(distinct t1.p_id) "c1",
count(distinct t2.sa_id) "c2",
count(distinct case when t2.sa_reference like '212%%' then t1.p_id else null end) "c3",
count(distinct case when t2.sa_reference like '212%%' then t2.sa_id else null end) "c4"
from capd_section t5,
capd_department t6,
capd_person t1,
capd_studentapplication t2,
capd_module t4,
capd_moduleapplication t3
where (t3.ma_studentapplication(+)=t2.sa_id) and
(t3.ma_module=t4.m_id(+)) and
(t4.m_modulesection=t5.s_id(+)) and
(t4.m_moduledept=t6.d_id(+)) and
(t4.m_reference not like '%%FTA%%') and
(t4.m_reference not like '%%HE%%') and
(t4.m_reference not like '%%PT%%') and
(t4.m_name not like 'NCTJ%%') and
(t4.m_reference not like 'ME%%') and
(t2.sa_student=t1.p_id)
having (count(distinct t3.ma_id)>0)