Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value at max date for a particular id

Tags:

date

sql

max

Here's my sql server table

ID       Date       Value 
___      ____       _____
3241     9/17/12    5
3241     9/16/12    100
3241     9/15/12    20
4355     9/16/12    12
4355     9/15/12    132
4355     9/14/12    4
1234     9/16/12    45
2236     9/15/12    128
2236     9/14/12    323
2002     9/17/12    45

This seems like it should be easy to do, but I don't know why I'm stuck. I'd like to select ONLY the max(date) and value at that max(date) for each id. I want to ignore all other dates that aren't the max(date) with respect to each id.

Here's what I'd like the table to look like:

ID       Date       Value 
___      ____       _____
3241     9/17/12    5
4355     9/16/12    12
1234     9/16/12    45
2236     9/15/12    128
2002     9/17/12    45

I tried group by using max(date), but it didn't group anything. I'm not sure what I'm doing wrong. Thanks in advance for the help!

like image 685
Deron S Avatar asked Sep 17 '12 17:09

Deron S


People also ask

How do I return a max value in SQL?

The MAX() function returns the largest value of the selected column.

Can I do a max on a date in SQL?

Can we use max with date in SQL? MAX function works with “date” data types as well and it will return the maximum or the latest date from the table.

Can we use MAX function in where clause?

The MAX() function is used with the WHERE clause to gain further insights from our data. In SQL, the MAX() function computes the highest or maximum value of numeric values in a column.

Which function is used to return the maximum value from Group of value?

MAX will return the largest value in a given list of arguments. From a given set of numeric values, it will return the highest value. Unlike MAXA function, the MAX function will count numbers but ignore empty cells, text, the logical values TRUE and FALSE, and text values.


3 Answers

You can use the following:

select t1.id, t2.mxdate, t1.value
from yourtable t1
inner join
(
  select max(date) mxdate, id
  from yourtable
  group by id
) t2
  on t1.id = t2.id
  and t1.date = t2.mxdate

See Demo

like image 137
Taryn Avatar answered Oct 16 '22 11:10

Taryn


This would give you what you need:

SELECT 
    m.ID,
    m.Date,
    m.Value
FROM 
    myTable m
    JOIN (SELECT ID, max(Date) as Date FROM myTable GROUP BY ID) as a
    ON m.ID = a.ID and m.Date = a.Date
like image 37
Vikdor Avatar answered Oct 16 '22 09:10

Vikdor


I have used this for avoiding join statement

WITH table1 
AS (SELECT
  id,
  Date,
  Value,
  ROW_NUMBER() OVER (PARTITION BY id ORDER BY Date DESC) AS rn
FROM yourtable)
SELECT
  *
FROM table1
WHERE rn = 1
like image 2
nvsk. avinash Avatar answered Oct 16 '22 09:10

nvsk. avinash