문제

I have a table like this

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

I tried below code to get first record from "AdID" group

;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

But it turns out the output like this

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

I want a output like this

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

Please help

도움이 되었습니까?

해결책

Please try order by ID instead of 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

다른 팁

This will help for this particular set of data:

;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

But I'd suggest to either change naming scheme for the photoname, or find some other ordering algoritm.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top