Hi I have a SQL table which has 6 columns, one of which is timestamp. I need to know how to retain only the row that has the most recent timestamp.
example:
Product|Price|Product_id|Stock_code|supplier|timestamp 1 |375 |xxyyxx |1234 |abcd |2020-05-05 1 |372 |xxyyxx |122 |abcd |2020-05-04 1 |372 |xxyyxx |122 |abcd |2020-05-05 1 |375 |xxyyxx |1234 |abcd |2020-05-07 1 |375 |xxyyxx |123 |abcd |2020-05-07 2 |420 |xxyyyx |1432 |bcda |2020-05-07 2 |420 |xxyyyx |1432 |bcda |2020-05-06 2 |420 |xxyyyx |1432 |bcda |2020-05-13
What I need my table to look like is
Product|Price|Product_id|Stock_code|supplier|timestamp 1 |375 |xxyyxx |1234 |abcd |2020-05-07 1 |372 |xxyyxx |122 |abcd |2020-05-05 1 |375 |xxyyxx |123 |abcd |2020-05-07 2 |420 |xxyyyx |1432 |bcda |2020-05-13
So I want to return the latest timestamp when all other variables are equal to each other over the two or more timestamps.
What to write to arrive at this? I have tried too many things which are just not working. pLease help
Advertisement
Answer
Simply do a GROUP BY
:
select Product, Price, Product_id, Stock_code, supplier, max(timestamp) from tablename group by Product, Price, Product_id, Stock_code, supplier