Question

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

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top