Using SQL Server 2005 / 2008 I have a table BB_MEDIAOBJECT (Id, ...), which includes several other data-fields for mediaobjects, a table BB_COLLECTION (Id, Name, Description) in which approx 30 collections are defined, and a table BB_MEDIAOBJECT_COLLECTION (MediaObjectId, CollectionId), Which lists all items in each collection.
Please help me with defining a SQL query that gives me the first 10 mediaobjects for each collection.
Based upon the answer supplied by Marc, I’ve ended up with the following end result, in which the query now correctly displays the 10 most recently modified items:
;WITH PartitionedComponents AS
(
SELECT
CollectionID = c.ID,
c.Name,
c.Description,
MediaObjectId = m.ID,
ROW_NUMBER() OVER(PARTITION BY c.ID ORDER BY m.modifiedby DESC) AS 'RowNum'
FROM
dbo.BEELDBANK_COLLECTION c
INNER JOIN
dbo.BEELDBANK_MEDIAOBJECT_COLLECTION mc ON mc.CollectionId = c.ID
INNER JOIN
dbo.BEELDBANK_MEDIAOBJECT m ON mc.MediaObjectId = m.Id
)
SELECT
CollectionID,
Name,
Description,
MediaObjectId
FROM
PartitionedComponents
WHERE
RowNum <= 10
One approach would be to use a CTE (Common Table Expression). You can partition your data by some criteria – i.e. your
Idfor the collection – and have SQL Server number all your rows starting at 1 for each of those partitions, ordered by some other criteria – i.e. probablyIdfor your media object (you didn’t specify exactly – you want the 10 first objects – but you didn’t say what these would be ordered by; first ten always implies there must be some order – change my CTE query as needed for your case!)So try something like this:
Here, I am selecting the first ten entries for each “partition” (i.e. for each
Id) – ordered in a descending fashion by theId(of MediaObjects).Does that approach what you’re looking for??