Search code examples
oracle-databaseaggregate-functionscubehaving-clauseoracle8i

NOT HAVING (inverse HAVING) clause with aggregation in Oracle


I am trying to filter the results of a GROUP BY CUBE using the HAVING clause. However I need to keep rows that do not meet a combination of conditions.

I intuitively tried:

SELECT [...]
FROM [...]
NOT HAVING (flag_1 = 1 AND flag_2 = 1 AND flag_3 = 1)
GROUP BY CUBE [...]

Sadly Oracle doesn't recognize NOT HAVING as valid syntax.

From a mathematical standpoint, inversing each individual condition does not yield the same result :

HAVING (flag_1 != 1 AND flag_2 != 1 AND flag_3 != 1)

How can I achieve the logical equivalent of NOT HAVING ?

Note: I found an existing question that was somewhat related, but it was specific to Microsoft Access and the goal was not the same, hence this new question­.


Solution

  • The mathematical inverse of your HAVING clause requires that you change the AND's to OR's and, if columns are nullable, null-check as well.

    EG (if nulls are possible):

    HAVING (nvl(flag_1,1) != 1 OR NVL(flag_2,1) != 1 OR NVL(flag_3,1) != 1)