1

我是 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 like '213%%')。(当年和上一年)

所以总共四个字段(c1,c2,c3,c4)。如果这有任何意义的话。甚至可能吗?

非常感谢您的帮助:)

4

2 回答 2

1

您可以简单地添加一个 or 语句来检查第二个值并尝试您的查询:

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);

在这里,我修改了您的条件,使用 as 子句检查这两个值((t2.sa_reference like '212%%')or (t2.sa_reference like '213%%'))。因此,如果满足任一条件,您就可以检索行。

于 2013-04-18T11:02:48.443 回答
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)
于 2013-04-18T11:08:35.167 回答