I am trying to use CASE and GROUP BY together to conditionally filter results only if they match the CASE criteria, and if they don't, return results as if there were no GROUP BY criteria specified.
Here's a simple model of what I have:
es.id | es.acct_num | p.id | p.name
1001 | 4306-0 | 1569 | The High School
1002 | 4306-0 | 1569 | The High School
665 | 5906-7 | 981 | Rec Center
783 | 5906-7 | 1221 | The Gym
and here's what I would like to see:
es.id | es.acct_num | p.id | p.name
1001 | 4306-0 | 1569 | The High School
1002 | 4306-0 | 1569 | The High School
0 | 5906-7 | 0 | MULTI-SITE
Since es.acct_num 5906-7 has more than 1 distinct associated p.id, I would like it grouped by the es.acct_num as 1 line item, then have the es.id, p.id represented by a '0', and have the p.name represented by the string 'MULTI-SITE'.
However, since es.acct_num 4306-0 only has exactly 1 distinct associated p.id, I would like these all returned as individual line items as if no grouping condition was applied.
The solution escapes me. How can I accomplish this?