-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,472
  • 16
  • 23
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,211
  • 17
  • 35
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – greg-449 Feb 01 '16 at 10:22
  • Thanks for ur comment. I will update in a minute :) @greg-449 – inverted_index Feb 01 '16 at 14:12
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

JassyJov
  • 180
  • 7