Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of HAVING in MySQL

Tags:

sql

mysql

I have a table from which I need to select all persons that have a first name that is not unique and that that set should be selected only if among the persons with a similar first name, all have a different last name.

Example:

FirstN    LastN
Bill      Clinton
Bill      Cosby
Bill      Maher
Elvis     Presley
Elvis     Presley
Largo     Winch

I want to obtain

FirstN    LastN
Bill      Clinton

or

FirstN    LastN
Bill      Clinton
Bill      Cosby
Bill      Maher

I tried this but it does not return what I want.

SELECT * FROM Ids
GROUP BY FirstN, LastN
HAVING (COUNT(FirstN)>1 AND COUNT(LastN)=1))

[Edited my post after Aleandre P. Lavasseur remark]

like image 326
KBrian Avatar asked Jun 21 '12 01:06

KBrian


People also ask

What is HAVING used for?

Having clause is used to filter data according to the conditions provided. Having clause is generally used in reports of large data. Having clause is only used with the SELECT clause.

Why is the HAVING clause in SQL?

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

Can I use HAVING and WHERE in SQL?

You can create a WHERE clause and HAVING clause involving the same column. To do so, you must add the column twice to the Criteria pane, then specify one instance as part of the HAVING clause and the other instance as part of the WHERE clause.

What is GROUP BY HAVING?

It groups the databases on the basis of one or more column and aggregates the results. After Grouping the data, you can filter the grouped record using HAVING Clause. HAVING Clause returns the grouped records which match the given condition. You can also sort the grouped records using ORDER BY.


2 Answers

WITH duplicates AS (
  SELECT firstn --, COUNT(*), COUNT(DISTINCT lastn)
    FROM ids
    GROUP BY firstn
    HAVING COUNT(*) = COUNT(DISTINCT lastn)
       AND COUNT(*) > 1
)
SELECT a.firstn, a.lastn
  FROM ids a INNER JOIN duplicates b ON (a.firstn = b.firstn)
  ORDER BY a.firstn, a.lastn

If mysql does not support WITH, then inner query:

SELECT a.firstn, a.lastn
  FROM ids a
      ,(SELECT firstn --, COUNT(*), COUNT(DISTINCT lastn)
          FROM ids
          GROUP BY firstn
          HAVING COUNT(*) = COUNT(DISTINCT lastn)
             AND COUNT(*) > 1
        ) b
  WHERE a.firstn = b.firstn
  ORDER BY a.firstn, a.lastn
like image 103
Glenn Avatar answered Sep 27 '22 18:09

Glenn


can you try this :

SELECT A.FirstN, B.LastN
FROM (
SELECT FirstN
FROM Ids
GROUP BY FirstN
HAVING (COUNT(FirstN)>1)
) AS A
INNER JOIN Ids B ON (A.FirstN = B.FirstN)
GROUP BY A.FirstN, B.LastN
HAVING COUNT(B.LastN)=1
like image 32
TTT Avatar answered Sep 27 '22 18:09

TTT