求一SQL查询语句(急)

来源:百度知道 编辑:UC知道 时间:2024/09/24 00:49:41
一个照片表Photoes,有PhotoTypeID(照片类别ID),PubTime(发布时间),PhotoPath(路径)字段,我想写一SQL语句,找出同一照片类别下,发布时间最早的,一个类别一条记录.如:
1 2009-7-15 img/01.jpg
1 2009-06-19 img/02.jpg
2 2009-05-21 img/03.jpg
2 2009-07-14 img/04.jpg
查询结果应为:
1 2009-06-19 img/02.jpg
2 2009-05-21 img/03.jpg

select a.* from Photoes a inner join (select PhotoTypeID,min(PubTime) as PubTime from Photoes group by PhotoTypeID) b on a.PhotoTypeID=b.PhotoTypeID and a.PubTime=b.PubTime

若是oracle,可使用分析函数

select *
from
(
select phototypeid,PubTime,PhotoPath
row_number() over(partition by phototypeid order by PubTime) rn
from photoes
)
where rn=1;

declare @Photoes table(PhotoTypeID int, PubTime varchar(10),PhotoPath varchar(20))

insert into @Photoes
select 1,'2009-7-15','img/01.jpg' union all
select 1,'2009-06-19','img/02.jpg' union all
select 2,'2009-05-21','img/03.jpg' union all
select 2,'2009-07-14','img/04.jpg'

select * from @Photoes

--按 PhotoTypeID 分组取 PubTime 最小的值所在行的数据
select a.* from @Photoes a
where PubTime = (select min(PubTime) from @Photoes where PhotoTypeID = a.PhotoTypeID) order by a.PhotoTypeID
<