--取每个代码日期最大的两条记录
create table #tbTest(dm varchar(10),rq datetime)
insert into #tbTest(dm,rq)
select '30-TF','2015-05-10' union all
select '30-TF','2015-05-14' union all
select '30-TF','2015-05-10' union all
select '30-TH','2015-05-10' union all
select '30-TH','2015-06-10' union all
select '30-TH','2015-06-14' union all
select '30-TH','2015-05-05' union all
select '30-TY','2015-05-18' union all
select '30-TY','2015-05-10' union all
--查询结果应该是
dm rq
30-TF 2015-05-14
30-TF 2015-05-10
30-TH 2015-06-14
30-TH 2015-06-10
30-TY 2015-05-18
30-TY 2015-05-10
谢谢大神
------解决思路----------------------
楼主贴出来的结果这样实现
CREATE TABLE #tbTest(dm varchar(10),rq datetime)
insert into #tbTest(dm,rq)
select '30-TF','2015-05-10' union all
select '30-TF','2015-05-14' union all
select '30-TF','2015-05-10' union all
select '30-TH','2015-05-10' union all
select '30-TH','2015-06-10' union all
select '30-TH','2015-06-14' union all
select '30-TH','2015-05-05' union all
select '30-TY','2015-05-18' union all
select '30-TY','2015-05-10'
GO
SELECT DISTINCT * FROM #tbTest AS a WHERE EXISTS(SELECT 1 FROM #tbTest WHERE dm=a.dm AND rq>a.rq HAVING COUNT(1)<=1 )
/*
30-TF 2015-05-10 00:00:00.000
30-TF 2015-05-14 00:00:00.000
30-TH 2015-06-10 00:00:00.000
30-TH 2015-06-14 00:00:00.000
30-TY 2015-05-10 00:00:00.000
30-TY 2015-05-18 00:00:00.000
*/
SQL2005以上用DENSE_RANK/ROW_NUMBER
SELECT DISTINCT dm,rq FROM (SELECT *,rn=DENSE_RANK()OVER(PARTITION BY dm ORDER BY rq DESC) FROM #tbTest AS a)AS Tab WHERE rn<=2
SELECT dm,rq FROM (SELECT *,rn=ROW_NUMBER()OVER(PARTITION BY dm ORDER BY rq DESC) FROM #tbTest AS a GROUP BY dm,rq)AS Tab WHERE rn<=2