SQL如何在select和having子句中重用case语句?

时间:2015-04-15 22:42:11

标签: sql oracle11g having-clause

我正在努力使我的查询变得更简单,性能更好(更快)。目前,数据超过1000万条记录需要很长时间!

我认为我可以通过不重复select和having子句中的case语句来实现它们(它们是相同的)。 我在select和having子句(fc.Activity_Amount)中有另一个重复的语句,我通过添加一个左连接(*)来删除它。但我不知道如何摆脱案件状态被使用两次?

我在where where子句中有更多的连接和相关条件。提到这一点,说明查询真的很复杂,需要很长时间才能执行! 100万条记录接近20分钟。

Select (Case When Aca2.Cycle_Activity_Amount Is Null Then 0 Else Aca2.Cycle_Activity_Amount End +
        Case When Aa.Activity_Amount Is Null Then 0 Else Aa.Activity_Amount End) As "TF",  
       Fc.Activity_Amount As Cap
From Account_Cycle_Activity Aca   
  Join school Ca On Aca.Account_Id = Ca.Account_Id 
  left join ( 
    SELECT ACCOUNT_ID, ACTIVITY_AMOUNT 
    FROM ACCOUNT_ACTIVITY 
    WHERE ACTIVITY_TYPE_CODE = '112' 
      and POINT_IN_TIME_CODE = 'YR1' 
  ) Aa On Aca.Account_Id = Aa.Account_Id
  Left Join (
    Select Account_Id, Cycle_Activity_Amount, Cycle_Ctr  
    From Account_Cycle_Activity 
    Where Activity_Type_Code = '112' 
      And Activity_Group_Code = '2CY'
  ) Aca2 On Aca.Account_Id = Aca2.Account_Id And Aca2.Cycle_Ctr=Ca.Cycle_Ctr

  Left Join ( 
     Select Activity_Amount, Account_Id 
     From Account_Activity 
     Where Activity_Type_Code = '113' And Point_In_Time_Code = 'YR1'
  ) Fc On Aca.Account_Id = Fc.Account_Id**

Where  Aca.Cycle_Ctr=Ca.Cycle_Ctr 
Group By  Aca2.Cycle_Activity_Amount,Aa.Activity_Amount,fc.Activity_Amount
Having (Case When Aca2.Cycle_Activity_Amount Is Null Then 0 Else Aca2.Cycle_Activity_Amount End + 
        Case When Aa.Activity_Amount Is Null Then 0 Else Aa.Activity_Amount End) >  fc.ACTIVITY_AMOUNT;

0 个答案:

没有答案