用这个代码就好啦
select * from a where Date in(select max(Date) from a group by Name)
这个慎散语句只雀核能解决你目前的问题﹐可能会有些宽岁氏情况实现不了﹐数据多的话还是ROW_NUMBER可以﹐
select ID,Name,Num,Date FROM (SELECT ROW_NUMBER() OVER(PARTITION BY Name ORDER BY Date DESC) RID ,* FROM a) TEMP WHERE RID=1
先mark,再想解决方案
先上代码,针对SQLSERVER
--insert test data
TRUNCATE table table1;
INSERT INTO Table1 伏伍VALUES ('ls',9,'2013-08-07')
INSERT INTO Table1 VALUES ('zs',2,'2013-08-09')
INSERT INTO Table1 VALUES ('ls',7,'2013-08-08')
INSERT INTO 缺帆或Table1 VALUES ('zs',3,'2013-08-10')
INSERT INTO Table1 VALUES ('ls',8,'2013-08-06')
select * from (
select ROW_NUMBER() over (
PARTITION BY Name order by [Date] desc
) as rn ,*
from Table1
) a
where rn =1
再上结果轿雀
rn ID Name Num Date
-------------------- ----------- ---------- ----------- ----------
1 3 ls 7 2013-08-08
1 4 zs 3 2013-08-10
思路是按名称分组,每组按日期倒序并将每个组添加行号,最后取出行号为1的记录即可
select id,name,num,date
from a
where (name,date) 敏好in (select name,max(date) from a group 中拿或by 卖伍name)
如果sql server,则是
with t as (select name,max(date) d from a group by name)
select id,name,num,date
from a
where exists(select * from t where a.name=t.name and a.date=t.d)
WITH t AS
( SELECT 1 ID,'zs' Name, 2 Num, '2013-08-09' d FROM dual
UNION ALL
SELECT 2 , 'zs' , 3 , '2013-08-10' FROM dual
UNION ALL
SELECT 3 ,'ls' , 9 ,'2013-08-07' FROM 郑纳派dual
UNION ALL
SELECT 4 ,'喊贺ls' , 7 , '2013-08-08' FROM dual
UNION ALL
SELECT 5 ,'ls' , 8 , 茄局'2013-08-06' FROM dual
)
SELECT id,
name,
num,
d
FROM
(SELECT t.*, rank() over (partition BY name order by d DESC) rn FROM t
)t2
WHERE t2.rn=1;
select id, distinct(name),num,date from a