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]
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.
The HAVING clause was added to SQL because the WHERE keyword cannot be used with aggregate functions.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With