Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
mcupryk
Yak Posting Veteran
91 Posts |
Posted - 2011-01-25 : 14:33:23
|
| I have the following query which returns multiple instances of the same user. I would like to make sure that the query returns the latest date instance.Any help would be great.SELECT TOP 100 [UserNameID] as ViewerUserNameID, ----- table tbl_ProfileViews [ViewUserNameID] as ViewedUserNameID, ----- table tbl_ProfileViews [TimeStamp] as ViewedDate, ----- table tbl_ProfileViews [PhotoID], ----- table tbl_Photos [ProfileID], ----- table tbl_Photos [p_Primary] ----- table tbl_PhotosFROM tbl_ProfileViewsINNER JOIN tbl_Photos ON tbl_Photos.ProfileID = tbl_profileViews.UserNameIDWHERE tbl_ProfileViews.ViewUserNameID = @ViewedUsernameID AND (@FromDate IS NULL OR (([TimeStamp] >= @FromDate) AND [TimeStamp] = (SELECT MAX([TimeStamp]) FROM tbl_ProfileViews A where A.UserNameID = tbl_profileViews.UserNameID)))ORDER BY [TimeStamp] DESCAny help would be awesome. |
|
|
jp.jetti
Starting Member
3 Posts |
Posted - 2011-01-25 : 16:01:22
|
| SELECT TOP 100A.[UserNameID] as ViewerUserNameID, ----- table tbl_ProfileViewsA.[ViewUserNameID] as ViewedUserNameID, ----- table tbl_ProfileViewsA.[TimeStamp] as ViewedDate, ----- table tbl_ProfileViewsB.[PhotoID], ----- table tbl_PhotosB.[ProfileID], ----- table tbl_PhotosB.[p_Primary] ----- table tbl_PhotosFROM tbl_ProfileViews A INNER JOIN tbl_Photos B ON A.UserNameID = B.ProfileIDWHERE A.ViewUserNameID = @ViewedUsernameID AND A.[TimeStamp] = (SELECT MAX(C.[TimeStamp] from tbl_ProfileViews C Where C.ViewUserNameID = @ViewedUsernameID) ORDER BY A.[TimeStamp] DESCI hope this will help you.You did the most. I just did aliasing.All the bestJP Jetti |
 |
|
|
|
|
|