create table #purchase(goodsid int,sdate datetime);
insert into #purchase
select 1,'2013-02-01'
union
select 1,'2013-02-02'
union
select 1,'2013-02-03'
union
select 2,'2013-02-01'
union
select 2,'2013-02-05'
union
select 2,'2013-02-06'
按GOODSID分组,显示最大两条sdate记录
1 2013-02-03 00:00:00.000 2013-02-02 00:00:00.000
2 2013-02-06 00:00:00.000 2013-02-05 00:00:00.000
------解决方案--------------------
create table #purchase(goodsid int,sdate datetime);
insert into #purchase
select 1,'2013-02-01'
union
select 1,'2013-02-02'
union
select 1,'2013-02-03'
union
select 2,'2013-02-01'
union
select 2,'2013-02-05'
union
select 2,'2013-02-06'
select a.*,b.sdate2
from
(
select goodsid ,max(sdate) as sdate from #purchase a group by goodsid
) a
left join
(
select a.goodsid , max(a.sdate) as sdate2 from #purchase a ,
(
select goodsid ,max(sdate) as sdate from #purchase group by goodsid
)b where a.goodsid=b.goodsid and a.sdate<>b.sdate group by a.goodsid
) b on a.goodsid=b.goodsid
goodsid sdate sdate2
----------- ----------------------- -----------------------
1 2013-02-03 00:00:00.000 2013-02-02 00:00:00.000
2 2013-02-06 00:00:00.000 2013-02-05 00:00:00.000
(2 行受影响)