I use the following query (in SQL Server 2008) to fetch the last 20 records from a table.
The query works as intended, my only problem is that this is a log table where a certain itemID
can appear several times. Is there a way that I can only select unique itemIDs here?
I tried using DISTINCT but this doesn't work here as not the whole rows are duplicates, just the itemID can appear multiple times (and then the time stamps or other data differ).
My SQL:
ALTER PROCEDURE [dbo].[RC_FetchUpdates]
@departmentID int
AS
BEGIN
SET NOCOUNT ON;
SELECT TOP 20 A.itemID,
A.lastUpdate,
CONVERT(VARCHAR(11), A.modTime, 106) AS modTime,
A.modBy,
B.itemName,
B.linkRef
FROM RC_LogLinks A
LEFT JOIN RC_Links B
ON B.itemID = A.itemID
WHERE B.departmentID = @departmentID
AND A.lastUpdate <> 'Deleted'
ORDER BY A.modTime desc, B.itemName
FOR XML PATH('updates'), ELEMENTS, TYPE, ROOT('ranks')
END