这可以变得更容易吗?

时间:2012-09-25 00:02:57

标签: sql

有更简单的方法吗?我只想要6年内至少有2个充电代码的家庭 - (cy =当前年份=去年等)?

Exists (SELECT * FROM ac_ViewMultiHouseholdChargeCodeYearCode AS VMH 
WHERE 
aa_Households.HouseholdID = VMH.HouseholdiD and 
VMH.ChargeCode = 'Dinner' and 
(VMH.ChargeCount_CY > 0 and
 (VMH.ChargeCount_LY > 0 or
  VMH.ChargeCount_2Y > 0 or 
  VMH.ChargeCount_3Y > 0 or 
  VMH.ChargeCount_4Y > 0 or 
  VMH.ChargeCount_5Y > 0)) or 
(VMH.ChargeCount_LY > 0 and 
 (VMH.ChargeCount_CY > 0 or
  VMH.ChargeCount_2Y > 0 or
  VMH.ChargeCount_3Y > 0 or 
  VMH.ChargeCount_4Y > 0 or
  VMH.ChargeCount_5Y > 0)) or
(VMH.ChargeCount_2Y > 0 and 
 (VMH.ChargeCount_LY > 0 or
  VMH.ChargeCount_CY > 0 or 
  VMH.ChargeCount_3Y > 0 or
  VMH.ChargeCount_4Y > 0 or
  VMH.ChargeCount_5Y > 0)) or
(VMH.ChargeCount_3Y > 0 and
 (VMH.ChargeCount_LY > 0 or 
  VMH.ChargeCount_2Y > 0 or
  VMH.ChargeCount_CY > 0 or
  VMH.ChargeCount_4Y > 0 or
  VMH.ChargeCount_5Y > 0)) or
(VMH.ChargeCount_4Y > 0 and
 (VMH.ChargeCount_LY > 0 or
  ChargeCount_2Y > 0 or
  VMH.ChargeCount_3Y > 0 or
  VMH.ChargeCount_CY > 0))) 

1 个答案:

答案 0 :(得分:5)

您可以将其简化为:

where (
  (case when VMH.ChargeCount_CY > 0 then 1 else 0 end) +
  (case when VMH.ChargeCount_LY > 0 then 1 else 0 end) +
  (case when VMH.ChargeCount_2Y > 0 then 1 else 0 end) +
  (case when VMH.ChargeCount_3Y > 0 then 1 else 0 end) +
  (case when VMH.ChargeCount_4Y > 0 then 1 else 0 end) +
  (case when VMH.ChargeCount_5Y > 0 then 1 else 0 end)
) >= 2