简体   繁体   中英

In SQL, how to select rows with matching values in one column, based on earliest date in another column

I think this should be a simple SQL exercise, but I am not sure how it is done as I am new to querying dbs with SQL. I have a table that looks like this:

select * from myschema.mytable

customer_name                   date
         nick    2017-06-19 19:26:40
          tom    2017-06-21 19:24:40
        peter    2017-06-23 21:25:10
         nick    2017-06-24 13:43:39

I'd like for this query to return only one row for each unique name. Specifically, I'd like the query to return the rows for each customer_name with the earliest date. In this case, the first row for nick should be returned (with date 2017-06-19), but not the other row with date 2017-06-24.

Is this a simple exercise in SQL?

Thanks!

A simple MIN will do:

SELECT
    customer_name,
    MIN(date) AS earliest_date
FROM myschema.mytable
GROUP BY customer_name;

For this kind of problems you can use aggregate functions. what has to be done basically is grouping the rows by name and choosing the minimum date:

select cutomer_name, MIN(date)
FROM myschema.mytable
GROUP BY customer_name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM