Wednesday, 27 May 2015

Mysql: Select where field has more than 2 non duplicated records sql



This should be pretty easy but I am just not able to figure this one out.
Got a table with customers order information. There is a field within this table called customers_email_address and customers_id along with a number of other non-essential fields. I need to locate distinct records where the entries in the customers_email_address field are different but unique to the same customers_id. In other words, I need to find out what customers have changed their email address in their account since their account's inception so I can update my email advertising program with their new email address. Something I didn't think of when the site was designed!
Maybe an example would be:
customers_ID    customers_email_address
1               joeschome@hotmail.com
2               frankj@hotmail.com
1               joeschome@hotmail.com
2               frankj@hotmail.com
1               joeschome@yahoo.com
2               frankj@yahoo.com
3               janefr@live.com
3               janefr@live.com
3               janefr@live.com

result of query should look like this:

customers_id    customers_email_address
1               joeschome@hotmail.com
1               joeschome@yahoo.com
2               frankj@hotmail.com
2               frankj@yahoo.com



Solution:
CREATE TABLE orders (`customers_ID` int, `customers_email_address` varchar(21));
   
INSERT INTO orders
    (`customers_ID`, `customers_email_address`)
VALUES
    (1, 'joeschome@hotmail.com'),
    (2, 'frankj@hotmail.com'),
    (1, 'joeschome@hotmail.com'),
    (2, 'frankj@hotmail.com'),
    (1, 'joeschome@yahoo.com'),
    (2, 'frankj@yahoo.com'),
    (3, 'janefr@live.com'),
    (3, 'janefr@live.com'),
    (3, 'janefr@live.com');


SELECT DISTINCT o.customers_id, o.customers_email_address
  FROM orders o JOIN
(
  SELECT customers_id
    FROM orders
   GROUP BY customers_id
  HAVING COUNT(DISTINCT customers_email_address) > 1
) q
    ON o.customers_id = q.customers_id
ORDER BY o.customers_id

0 comments:

Post a Comment