0

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
halfer
  • 19,824
  • 17
  • 99
  • 186
user2571510
  • 11,167
  • 39
  • 92
  • 138

1 Answers1

2

It will be something like this:

WITH rankedLogLinks AS (
    SELECT ROW_NUMBER() OVER (PARTITION BY A.itemID ORDER BY A.modTime DESC) AS rownum, A.itemID, A.lastUpdate, A.modTime, A.modBy
    FROM RC_LogLinks A
    WHERE A.lastUpdate <> 'Deleted'
)
SELECT  r.itemID, r.lastUpdate, CONVERT(VARCHAR(11), r.modTime, 106) AS modTime, r.modBy, B.itemName, B.linkRef
FROM rankedLogLinks r
    LEFT JOIN   RC_Links B
       ON B.itemID = r.itemID
    WHERE B.departmentID = @departmentID
       AND r.rownum = 1
    ORDER BY B.itemName
    FOR XML PATH('updates'), ELEMENTS, TYPE, ROOT('ranks')
;

You might want to change the location of WHERE A.lastUpdate <> 'Deleted' from the first query to the second depending on your requirement.

Rashmi Pandit
  • 23,230
  • 17
  • 71
  • 111