有更简单的方法吗?我只想要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)))
答案 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