-2

My Table:

Date              Code        Rate
----              ----        ----
2015-01-01          1         100
2015-01-01          2         200
2015-01-01          3         300
2015-06-01          1         150

How can i get the latest rates(By Date), like:

Date              Code        Rate
----              ----        ----
2015-01-01          2         200
2015-01-01          3         300
2015-06-01          1         150

SQL Query?

kish
  • 23
  • 4

3 Answers3

1
WITH cte AS (
    SELECT 
        *,
        ROW_NUMBER() OVER (PARTITION BY Code ORDER BY Date DESC) rn
    FROM yourtable
)
SELECT 
        Date, 
        Code, 
        Rate
FROM cte 
WHERE rn=1
Dzmitry Paliakou
  • 1,587
  • 19
  • 27
0

You can do it with sub-query Try this:

SELECT * FROM (
    SELECT * FROM your_table ORDER BY date DESC LIMIT 5
) sub
ORDER BY date ASC

This code gets the last 5 rows from your table.

inverted_index
  • 2,329
  • 21
  • 40
0

Try this:

select  Date,
        Code,
        Rate
from    (
            select  ROW_NUMBER() over(partition by    code order by   date desc)as Id,date,code,rate
            from    yourTable
        ) x
where   Id = 1
order by    date
General Grievance
  • 4,555
  • 31
  • 31
  • 45
JassyJov
  • 204
  • 1
  • 9