Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HAVING clause: at least one of the ungrouped values is X

Example table:

Col1 | Col2
A    | Apple
A    | Banana
B    | Apple
C    | Banana

Output:

A

I want to get all values of Col1 which have more than one entry and at least one with Banana.

I tried to use GROUP BY:

SELECT Col1
FROM Table
GROUP BY Col1
HAVING count(*) > 1
AND ??? some kind of ONEOF(Col2) = 'Banana'

How to rephrase the HAVING clause that my query works?

like image 994
D.R. Avatar asked Nov 25 '15 14:11

D.R.


People also ask

What is the HAVING clause?

A HAVING clause restricts the results of a GROUP BY in a SelectExpression. The HAVING clause is applied to each group of the grouped table, much as a WHERE clause is applied to a select list. If there is no GROUP BY clause, the HAVING clause is applied to the entire result as a single group.

Can you use HAVING clause without GROUP BY?

Having can be used without groupby clause,in aggregate function,in that case it behaves like where clause. groupby can be used without having clause with the select statement. 3. The having clause can contain aggregate functions.

What does HAVING clause mean in SQL?

A HAVING clause in SQL specifies that an SQL SELECT statement must only return rows where aggregate values meet the specified conditions.

Can we use GROUP BY and HAVING clause together?

HAVING Clause always utilized in combination with GROUP BY Clause. HAVING Clause restricts the data on the group records rather than individual records. WHERE and HAVING can be used in a single query.


2 Answers

Use conditional aggregation:

SELECT Col1
FROM Table
GROUP BY Col1
HAVING COUNT(DISTINCT col2) > 1 AND 
       COUNT(CASE WHEN col2 = 'Banana' THEN 1 END) >= 1

You can conditionally check for Col1 groups having at least one 'Banana' value using COUNT with CASE expression inside it.

Please note that the first COUNT has to use DISTINCT, so that groups with at least two different Col1 values are detected. If by having more than one entry you mean also rows having the same Col2 values repeated more than one time, then you can skip DISTINCT.

like image 67
Giorgos Betsos Avatar answered Sep 18 '22 17:09

Giorgos Betsos


SELECT Col1
FROM Table
GROUP BY Col1
HAVING count(*) > 1
AND Col1 in (select distinct Col1 from Table where Col2 = 'Banana');
like image 33
Nir Levy Avatar answered Sep 19 '22 17:09

Nir Levy