Reputation: 11
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
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
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
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
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