3

Struggling with what's probably a very simple problem. I have a query like this:

 ;WITH rankedData
       AS ( -- a big, complex subquery)
  SELECT UserId,
         AttributeId,
         ItemId
  FROM   rankedData
  WHERE  rank = 1
  ORDER  BY datEventDate DESC

The sub-query is designed to grab a big chunk of interlined data and rank it by itemId and date, so that the rank=1 in the above query ensures we only get unique ItemIds, ordered by date. The partition is:

Rank() OVER (partition BY ItemId ORDER BY datEventDate DESC) AS rk

The problem is that what I want is the top 75 records for each UserID, ordered by date. Seeing as I've already got a rank inside my sub-query to sort out item duplicates by date, I can't see a straightforward way of doing this.

Cheers, Matt

4

1 回答 1

6

我认为您的查询应该看起来像

SELECT t.UserId, t.AttributeId, t.ItemId
FROM (
SELECT UserId, AttributeId, ItemId, rowid = ROW_NUMBER() OVER (
        PARTITION BY UserId ORDER BY datEventDate 
        ) 
FROM rankedData
) t
WHERE t.rowid <= 75
于 2013-05-21T11:05:12.847 回答