Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple aggregate functions in HAVING clause

Tags:

sql

mysql

count

Due to the nature of my query i have records with counts of 3 that would also fit the criteria of having count of 2 and so on. I was wondering is it possible to query 'having count more than x and less than 7' ? How could I write this. Here is my current code.

GROUP BY meetingID HAVING COUNT( caseID )<4 

I'd like something like

GROUP BY meetingID HAVING COUNT( caseID )<4 AND >2 

That way it would only count for exactly 3

like image 896
blarg Avatar asked Feb 07 '13 16:02

blarg


People also ask

Can we use aggregate functions in HAVING clause?

The SQL HAVING Clause The HAVING clause was added to SQL because the WHERE keyword cannot be used with aggregate functions.

Can we use multiple aggregate function in GROUP BY clause?

This is because GROUP BY will only return unique results per group and the SELECT list can only consist aggregate functions or columns that are part of the GROUP BY clause. So depending on what you want to get, you can use different functions to get the optimal output.

Can we give two conditions in HAVING clause?

The HAVING clause is applied nearly last, just before items are sent to the client, with no optimization. In other words, it is applied after the grouping operation has been performed (in contrast with WHERE , which is performed before any grouping operation).

Can HAVING have multiple conditions SQL?

The SQL AND condition and OR condition can be combined to test for multiple conditions in a SELECT, INSERT, UPDATE, or DELETE statement. When combining these conditions, it is important to use parentheses so that the database knows what order to evaluate each condition.


2 Answers

GROUP BY meetingID HAVING COUNT(caseID) < 4 AND COUNT(caseID) > 2 
like image 118
Trent Earl Avatar answered Oct 02 '22 12:10

Trent Earl


There is no need to do two checks, why not just check for count = 3:

GROUP BY meetingID HAVING COUNT(caseID) = 3 

If you want to use the multiple checks, then you can use:

GROUP BY meetingID HAVING COUNT(caseID) > 2  AND COUNT(caseID) < 4 
like image 27
Taryn Avatar answered Oct 02 '22 13:10

Taryn