Friday, August 21, 2009

Code: TSQL Select unique data

SELECT   Top(5) *
FROM [Reports].[Reporting].[ReportTracking]
WHERE ReportTrackingId IN
(
SELECT MAX(ReportTrackingId)
FROM [Reports].[Reporting].[ReportTracking]
WHERE UserId = 41603
GROUP BY ReportName
)
ORDER BY ReportTrackingId DESC

The SQL above can be used as a basis when you need to select data from your database that needs to contain only unique values for a particular column.  The inner query will retrieve the newest primary keys based on your unique column and the outer query grabs the entire row for that primary key.