数据库的一个表里筛选出每一人的时间最新的一条记录
CREATE TABLE #data
(
yhh VARCHAR(20),
name VARCHAR(12),
gdcs INT,
gdsj1 DECIMAL(5,2),
gdtime DATETIME
)
GO
INSERT INTO #data
SELECT '600040407' , '王玲' , 1 , 0.56 , '2011/6/21 22:34 '
union
SELECT '600040407' , '王玲' , 2 , 0.56 , '2011/6/24 10:21 '
union
SELECT '600040407' , '王玲' , 3 , 0.56 , '2011/12/7 10:45 '
union
SELECT '600040407' , '王玲' , 4 , 0.56 , '2012/1/15 14:01 '
union
SELECT '600040407' , '王玲' , 5 , 0.56 , '2012/12/26 14:11 '
union
SELECT '600040408' , '魏武' , 1 , 0.56 , '2011/6/21 22:36 '
union
SELECT '600040408' , '魏武' , 2 , 0.56 , '2013/11/15 10:46 '
union
SELECT '600040408' , '魏武' , 4 , 0.56 , '2014/1/19 9:12 '
union
SELECT '600040408' , '魏武' , 3 , 0.56 , '2014/1/10 13:57 '
union
SELECT '600040408' , '魏武' , 5 , 0.56 , '2014/1/22 10:08 '
union
SELECT '600040435' , '于洋 ' , 1 , 0.56 , '2011/6/22 12:54 '
union
SELECT '600040408' , '魏武' , 2 , 0.56 , '2013/3/11 9:16 '
union
SELECT '600040408' , '魏武' , 4 , 0.56 , '2014/1/10 11:18 '
union
SELECT '600040408' , '魏武' , 3 , 0.56 , '2013/12/20 15:09 '
GO
---- 方法1
select a.*
from #data a
where not exists(select 1
from #data b
where b.name=a.name and b.gdtime>a.gdtime)
--方法2
SELECT a.*
FROM #data a
INNER JOIN ( SELECT name ,
MAX(gdtime) 'maxgdtime'
FROM #data
GROUP BY name
) b ON a.name = b.name
AND a.gdtime = b.maxgdtime;
go
SELECT * FROM #data
GO
DELETE #data
GO
DROP TABLE #data