Question

I have to table One is for User and second is Image. There are many row in Image table for Same Uid. How to find distinct record according to Uid.

User 
ID , int
Date Date

Image 
ImageID int
ImageStatus int
Uid  int  (reference from  User Table)
ImagePath varchar(50)

i am using below query but its giving more than one row for UId

select I.Uid, I.ImagePath, I.status from user u inner join Image I on u.Uid=I.Uid  order by u.Date desc
Was it helpful?

Solution

Try using Row_number() with Partition

;with cte as
(
select I.Uid, I.ImagePath,rn=row_number()over(partition by I.Uid order by u.Date desc), I.status from user u inner join Image I on u.Uid=I.Uid
)

select * from cte where rn=1

OTHER TIPS

You do not need to do the join but instead can find the distinct UID in image table.

select distinct I.Uid from Image I;

Or if you want to list the specific columns distinctly:

select distinct I.Uid, I.ImagePath, I.status from Image I order by u.Date desc;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top