Link to home
Start Free TrialLog in
Avatar of heyday2004
heyday2004

asked on

How to use complicated nested case statements?

I have a SQL statement to calculate some stats data for analytical report purpose, it's working good:

select
SUM(CASE WHEN (createDate = CURRENT_DATE AND exitDate IS NULL) THEN 1 ELSE 0 END)
...
from sample table
group by ...

Now I want to add more complicated logic to the script (adding nested "AND" and "OR" logic), something like:

select
SUM(CASE WHEN (createDate = CURRENT_DATE) AND (exitDate IS NULL OR (exitDate > CURRENT_DATE)) THEN 1 ELSE 0 END) AS survey_Tasks_Started_And_Not_Completed,
...
from sample table
group by...

The purpose is, when createDate = CURRENT_DATE, I want to include records of both (exitDate field is null) or (exitDate is later than today)

But seems it's not working if I add too many parenthesis and nested statements... Any solution for this kind of issue when adding complicated nested case statements in MySQL?

Or is there any recommendation for better solution for such common scenarios since too many nested level cause issue too?

Thanks!
SOLUTION
Avatar of Dale Burrell
Dale Burrell
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Avatar of Aaron Tomosky
Aaron Tomosky
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of heyday2004
heyday2004

ASKER

Thanks, any further suggestion on the best practice to deal with such complicated nested scenario? I think it's very error-prone.  Thanks.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks.