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!
The MAX() function returns the largest value of the selected column.
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.
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.
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.
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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With