How to get the latest data from a cell for each person who meets the condition?

I have a table that looks like this:

Name    Type   Date     Value
-------------------------------- 
Emilia  1   2010-11-02  10
Eva     0   2009-07-05  11
Monica  1   2010-04-22  12
Emilia  0   2011-07-12  13
Monica  1   2012-05-01  14
Eva     1   2006-02-12  15
Monica  0   2004-12-12  16
Emilia  1   2005-11-11  17
Eva     1   2014-02-01  18
Emilia  1   2015-03-11  19
Monica  0   2002-11-28  20

I need a table that displays a list of all women who have type 1 on the last date, and a value for that date. So the table I want to query should look like this:

Name   Value
------------
Emilia 19
Eva    18

So basically I need to find out what is the last date for each person, then check if type 1 is, and if so, I need to display the data from the Value column.

Please help me because I do not know how to do this.

+4
source share
2 answers

To do this, use the window function ROW_NUMBER.

:with CTE as
(
select *,Row_Number() over(partition by Name order by [Date] desc) RN
From Yourtable
)   
select Name,Value from cte 
where RN=1 and Type = 1
+3
source
declare @t table (name varchar(10),type int,date date, valu int)

insert into @t(name,type,date,valu)values ('Emilia',1,'2010-11-02',10)
insert into @t(name,type,date,valu)values ('Emilia',0,'2015-03-11',10)
insert into @t(name,type,date,valu)values ('Emilia',1,'2015-11-11',19)
insert into @t(name,type,date,valu)values ('Eva',0,'2006-02-12',10)
insert into @t(name,type,date,valu)values ('Eva',1,'2014-02-01',20)

SELECT a.*
FROM @t a 
INNER JOIN (SELECT type,MAX(date) AS LatestDate FROM @t GROUP BY type)b 
ON a.type = b.type
AND a.date=b.LatestDate
0
source

All Articles