Query to show most recent value based on the date field

Greetings, I need help with a very fundamental technique. Once I understand this technique Ill be able to transpose it to the situation at hand where I need to do this. I simply need to list the most recent value for each employee here... the value at each person's maximum date

Sample Detail Data:

EmpID                   Date                      Value

1                              1/1/14                   27

1                              2/12/15                333

2                              5/5/15                   255

3                              5/4/15                   110                        

3                              1/1/13                   67                          

3                              3/2/14                   80

4                              4/3/15                   9

4                              1/5/13                   6             

5                              4/5/24                   144                        

5                              1/5/15                   27          

5                              6/12/15                544

5                              3/1/13                   77


What is the most efficient way to display the most recent value for each employee ID via MS SQL.?

Many Thanks!

June 18th, 2015 9:12pm

;WITH cte AS
(
	SELECT *,
		ROW_NUMBER() OVER (PARTITION BY EmpId ORDER BY Date DESC) AS RN
	FROM
		Employees
)
SELECT
	EmpId, Date, VALUE 
FROM
	cte
WHERE
	RN = 1;

Alternatively 

SELECT
	a.EmpId,
	b.Date,
	b.VALUE
FROM
	Employees a
	CROSS APPLY
	(
		SELECT TOP (1)
			Date,
			VALUE
		FROM
			Employees b
		WHERE 
			b.EmpId = a.EmpId
		ORDER BY
			Date DESC 
	) b;

  • Proposed as answer by Rafael Juca 13 hours 20 minutes ago
Free Windows Admin Tool Kit Click here and download it now
June 18th, 2015 9:31pm

Give this a go:

DECLARE @table TABLE (empID INT, date DATE, value INT)
INSERT INTO @table (empID, date, value) VALUES
(1, '1/1/14 ', 27 ),(1, '2/12/15', 333),(2, '5/5/15 ', 255),(3, '5/4/15 ', 110),(3, '1/1/13 ', 67 ),(3, '3/2/14 ', 80 ),(4, '4/3/15 ', 9),(4, '1/5/13 ', 6  ),(5, '4/5/24 ', 144),(5, '1/5/15 ', 27 ),
(5, '6/12/15', 544),(5, '3/1/13 ', 77 )

SELECT *
  FROM @table t
 WHERE date = (SELECT MAX(date) FROM @table WHERE empID = t.empID)

June 18th, 2015 9:39pm

Outstanding! I tried all 3 methods and they worked just fine (not sure which to rate the most helpful as they all were very effective and I am sure depending on the circumstances there is a place for each). Many Thanks!!!
Free Windows Admin Tool Kit Click here and download it now
June 19th, 2015 1:33pm

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics