TheReijo99
TheReijo99

Reputation: 11

SQL query for getting only the latest data

I would like to make a SQL query where I am only able to see my latest shipments. Currently I get the following result.

item    date        licence plate number
1       13.5.2016   abc-123
2       13.5.2016   abc-123
3       10.5.2016   xyz-567
1       20.4.2016   abc-123
2       20.4.2016   abc-123
6       10.5.2016   xyz-567

However I would like to only get the latest shipments based on the licence plate number. The wanted output would look like

item    date        licence plate number
1       13.5.2016   abc-123
2       13.5.2016   abc-123
3       10.5.2016   xyz-567

Upvotes: 1

Views: 113

Answers (4)

Sandeep Kumar
Sandeep Kumar

Reputation: 1202

You have to first find our the max date of each plate number then join the tables.

You can use below query.

select t2."item",t1."date",t1."licence plate number" from (
(select max("date") as date, "licence plate number" from Table_1 group by 
"licence plate number")) t1
 left join Table_1 t2 
on (t1."date" =  t2."date" and t1."licence plate number" =  t2."licence plate number")

The output of this query will be.

1      2016-05-13      abc-123
2      2016-05-13      abc-123
3      2016-05-10      xyz-567
6      2016-05-10      xyz-567

Upvotes: 0

user330315
user330315

Reputation:

The following is standard SQL supported by a wide range of DBMS:

select item, date, licence_plate_number
from (
    select item, date, licence_plate_number, 
           row_number() over (partition by licence_plate_number order by date desc as rn)
    from the_table
) t
where rn = 1
order by item;

Using a window function is typically faster than a self join with an aggregate.

Upvotes: 1

Max Fesenko
Max Fesenko

Reputation: 143

Maybe this helps:

SELECT TOP 10 --change 10 to any desired number to be viewed 
*
FROM YourDatabaseName 
ORDER BY Date DESC

Upvotes: 0

Giorgos Betsos
Giorgos Betsos

Reputation: 72165

You can use the following query:

SELECT t1.*
FROM mytable AS t1
JOIN (
   SELECT item, MAX("date") AS "date"
   FROM mytable
   GROUP BY item
) AS t2 ON t1.item = t2.item AND t1."date" = t2."date"

The query uses a derived table which selects the latest date per item. Using this derived table we can select the record that corresponds to this date.

Upvotes: 3

Related Questions