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`;
SELECT
customer_id
FROM
accounts
GROUP BY
customer_id
HAVING
COUNT(DISTINCT salesmanager_id) > 1
This basically gets all of the salesmanager_id
s of each customer_id
and if there is more than one unique salesmanager_id
value, the customer_id
is returned.
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