Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the "exotic" value in a MySQL table

Tags:

sql

mysql

count

I have a MySQL table called accounts. Within this table is a field called salesmanager_id. 99% of the time, the value in this field is always the same for all accounts of a specific customer (specified with customer_id).

What I'm trying to do is find the customer_id for the customers that have accounts assigned to more than one salesmanager. For example:

+------------------------------------+
| id | customer_id | salesmanager_id |
|------------------------------------|
| 1  | 12          | 4               |
| 2  | 12          | 4               |
| 3  | 14          | 3               | <-- I want this customer_id
| 4  | 14          | 4               |
+------------------------------------+

In the above example, customer_id 14 has both salesmanager_id 3 and 4 assigned to it. I would like to retrieve that customer_id for my list.

I tried the following query, but that returns an empty result (while I'm sure there are at least some differences).

SELECT `name`, `customer_id` AS `customer`, `salesmanager_id` FROM `accounts`
WHERE `salesmanager_id` NOT IN (
    SELECT `salesmanager_id` FROM `accounts` a
    LEFT JOIN `customers` c ON (a.customer_id = c.id)
    WHERE a.customer_id=c.id
) GROUP BY `customer`;
like image 909
Oldskool Avatar asked Jun 20 '12 08:06

Oldskool


1 Answers

SELECT 
    customer_id
FROM 
    accounts
GROUP BY 
    customer_id
HAVING 
    COUNT(DISTINCT salesmanager_id) > 1

This basically gets all of the salesmanager_ids of each customer_id and if there is more than one unique salesmanager_id value, the customer_id is returned.

like image 65
Zane Bien Avatar answered Nov 12 '22 19:11

Zane Bien