2

I have a table that is as follows:

  id value  date
  ---------------
  a, test,  01-01-15
  a, test,  01-02-15
  a, test,  01-03-15
  a, test1, 01-04-15
  a, test1, 01-05-15
  b, test, 01-01-15
  b, test, 01-02-15 

I need to write a query to be able to grab the latest mapping for both a & b

for instance, I want my results to be as follows:

a, test1, 01-05-15
b, test,  01-02-15

I can't seem to wrap my head around how to accomplish this

select max(date) 

only returns the latest date value

and select max(date), value group by value obviously does not return the id column

Prerak Sola
  • 9,517
  • 7
  • 36
  • 67
Just_Some_Guy
  • 330
  • 5
  • 24

3 Answers3

1

If your database supports Row_number then use this

select id,value,date from 
(
select row_number() over(partition by value order by date desc) as RN,
       id,value,date
from yourtable
) A
where RN=1

another way is by joining the result back to the table.

SELECT A.id, 
       A.value, 
       A.date 
FROM   yourtable A 
       INNER JOIN (SELECT Max(date) AS date, 
                          value 
                   FROM   yourtable 
                   GROUP  BY value) B 
               ON A.date = b.date 
                  AND A.value = B.value 
Pரதீப்
  • 91,748
  • 19
  • 131
  • 172
1

Depending on what version of SQL you use, you may have a function called ROW_NUMBER() OVER() that can help.

WITH x AS
(SELECT id, value, date 
        , ROW_NUMBER() OVER (PARTITION BY id ORDER BY date DESC) AS RowNum
FROM table
)
SELECT id, value, date
FROM x
WHERE RowNum = 1

The above would work in SQL Server and anything else that supports CTE and Windowing Functions. You could also write it as a derived table like this:

SELECT id, value, date FROM (SELECT id, value, date , ROW_NUMBER() OVER (PARTITION BY id ORDER BY date DESC) AS RowNum FROM table ) AS x WHERE RowNum = 1

1

Simple

SELECT DISTINCT ON (id) *
FROM   tbl
ORDER  BY id, date DESC NULLS LAST;

Detailed explanation:

Fast

For data distributions with many rows per id:

Community
  • 1
  • 1
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228