简体   繁体   中英

SQL How would I select the row with the largest of one field in several nearly-identical rows?

Let's say I have three rows with the following data on contracts for buying fruit in bulk.

NAME ---- LOCATION ---- EXPIRATION DATE
Apples    Pittsburgh    10/10/2015
Apples    Pittsburgh    1/2/2016
Apples    Pittsburgh    12/31/2015

If I had a huge list of entities like these where some of the fruits had multiple entries and I wanted to always choose the latest contract expiration date, what would I put in a SQL select query?

So out of those 3 entities, I want the final row (and the only one to show up in the select query) to be the one with the LATEST expiration date... in this example it would be the one with the EXPIRATION DATE of "1/2/2016"

As you describe the question, the solution is a simple group by :

select name, max(expirationdate)
from contracts t
group by name;

This assumes that the expiration date is stored in a native date/time format in the table. Storing dates using the proper type is so important that you should change the type if someone mistakenly gave it a string type. Look at the ALTER TABLE command for your database.

perhaps

 select "NAME", "LOCATION", MAX( "EXPIRATION DATE" ) from MyTable 
 group by "NAME", "LOCATION" 

if you want to separate addresses too, or

 select "NAME", "LOCATION", MAX( "EXPIRATION DATE" ) from MyTable 
 group by "NAME"

if you only need by-fruit maximum, among all the locations at once

check the demo and tune it to your needs: http://sqlfiddle.com/#!5/87599/5/0

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