Search code examples
mysqldistinct

SQL Query Selecting Multiple Columns Using Distinct on One Column Only (different desired outcome)


There is a same title as mine, but the desired result is different, so please excuse my new thread.

In short, I wanted to select two columns from a table, and I wanted to remove duplicates from one column only.

But since it's input from multiple users, there are typos and different writing of their names, so I wanted to ignore the distinct names but want to use DISTINCT on the phone number, while also adding the country code.

I've checked and tried multiple sources.

I tried putting the DISTINCT on one column only, such as:

SELECT
    buyer_name,
    DISTINCT(concat('62', phone_number) as phone_number),

But it came as an error.

Then I got advised by my manager that I should put the DISTINCT beside the SELECT:

SELECT DISTINCT
    buyer_name,
    concat('62', phone_number) as phone_number,

But the typo names are still shown, therefore, duplicate numbers still happen.

Sample data:

buyer_name      phone_number
Doni            6281234567
sofia           6281234568
Sofia           6281234568
Sophia          6281234568

Desired outcome:

buyer_name      phone_number
Doni            6281234567
sofia           6281234568

Solution

  • The following query should come up with your desired result.

    DBFiddle link: https://dbfiddle.uk/ctqwb-rC

    SELECT
        MIN(buyer_name) AS buyer_name,
        phone_number
    FROM
        users
    GROUP BY
        phone_number;