views:

40

answers:

2

Dear all,

I am trying to filter (or count) companies with multiple contact persons from a table containing a company_id and a person_id. Currently I just do this:

SELECT DISTINCT company_id,person_id FROM mytable GROUP BY company_id ORDER BY company_id

as well as

SELECT DISTINCT company_id FROM mytable

The first query returns a couple of rows more. Hence it is obvious that there are companies with multiple contact persons. From the different row count between the two queries I can even tell how many of them. Though I´d like to know how I can select exactly those companies that have more than one person_id assigned.

Thx in advance for any help!

+3  A: 

How about this?

SELECT company_id, COUNT(DISTINCT person_id)
FROM mytable
GROUP BY company_id
HAVING COUNT(DISTINCT person_id) > 1
eumiro
and usually I do `ORDER BY COUNT(DISTINCT person_id) DESC`.
Benoit
wow, that was quick. "You can accept the answer in 2 minutes". That never happened to me before. Not knowing about HAVING prevented rookie one from finding the obviously obvious. Thx eumiro and Benoit!
ran2
A: 
SELECT
   company_id
FROM
   mytable
GROUP BY
   company_id
HAVING
   COUNT(person_id) > 1
ORDER BY
   company_id
gbn