Pregunta

Say I have a table with data like this:

+------------------------------+------------+---------+
| email                        | uname      | credits |
+------------------------------+------------+---------+
| 824@hotmail.com              | barbra     |       6 |
| 123@gmail.com                | smith      |      25 |
| 123@gmail.com                | smithy     |      30 |
| abc@hotmail.com              | another    |      25 |
| def@comcast.net              | rob        |       8 |
| abc@hotmail.com              | ben        |      62 |
| ijk@yahoo.com                | jeb        |       2 |
| ijk@yahoo.com                | joe        |       5 |
+------------------------------+------------+---------+

So there is duplicate emails, and you want to send a newsletter out. But you don't want to send multiple of the email to the same email address, and you want to have their username in the email. You probably need to address the user in the email by the username which has more credits, as that account is more likely to be active. So you want a query that'll return data like this:

+------------------------------+------------+---------+
| email                        | uname      | credits |
+------------------------------+------------+---------+
| 824@hotmail.com              | barbra     |       6 |
| 123@gmail.com                | smithy     |      30 |
| def@comcast.net              | rob        |       8 |
| abc@hotmail.com              | ben        |      62 |
| ijk@yahii.com                | joe        |       5 |
+------------------------------+------------+---------+

So it picks the username that has more credits on their account.

How can I write a query to do this? The only examples I've seen are ones that don't care which username it picks, so you could get the user with less credits.

¿Fue útil?

Solución

Could you try this?

Select tab.email, tab.uname
From(
    Select email, max(credits) as credits
    From tab
    Group by  email
) x join tab on x.email = tab.email and tab.credits = x.credits

Otros consejos

This should do it:

SELECT email,uname,MAX(credits) "credits" FROM MY_TABLE GROUP BY email;

EDIT:

This question has some useful information. Try this instead:

SELECT `mytab`.`email`, `mytab`.`uname`, `mytab`.`credits`
FROM `my_table` `mytab`
INNER JOIN (
  SELECT `email`, MAX(`credits`) `max_cred`
  FROM `my_table`
  GROUP BY `email`
) `max` ON `mytab`.`email` = `max`.`email` AND `mytab`.`credits` = `max`.`max_cred`;
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top