Sql Server - 从组中获取第一条记录

时间:2014-04-25 11:20:50

标签: sql sql-server greatest-n-per-group

我有一张这样的表

http://i.imgur.com/2uLQBT0.jpg

我尝试使用下面的代码来获取#34; AdID"小组

;with cte as
(
  select
    ADID,
    PhotoName,
    PhotoPath,
    rank() over(partition by AdID order by PhotoName) as rn
  from AdPhoto
)  
select ADID,
    PhotoName,
    PhotoPath
from cte
where rn = 1

但结果是这样的输出

AD1001  temptemp_1.jpeg ~/UserUploads/temptemp/
AD1002  temptemp_10.jpg ~/UserUploads/temptemp/

我想要这样的输出

AD1001  temptemp_1.jpeg ~/UserUploads/temptemp/
AD1002  temptemp_5.jpg  ~/UserUploads/temptemp/

请帮忙

2 个答案:

答案 0 :(得分:2)

请尝试使用order by ID代替order by PhotoName

;with cte as
(
  select
    ADID,
    PhotoName,
    PhotoPath,
    rank() over(partition by AdID order by ID) as rn
  from AdPhoto
)  
select ADID,
    PhotoName,
    PhotoPath
from cte
where rn = 1

答案 1 :(得分:0)

这将有助于这组特定的数据:

;with cte as
(
  select
    ADID,
    PhotoName,
    PhotoPath,
    rank() over(partition by AdID order by len(PhotoName) asc, PhotoName) as rn
  from AdPhoto
)  
select ADID,
    PhotoName,
    PhotoPath
from cte
where rn = 1

但是我建议要么改变光子命名的命名方案,要么找一些其他的排序算法。