2013-05-27 79 views
1

我們有一個顯示在我們的儀表板上的前十個視頻列表。有時我們有一種情況,一個用戶發佈了6個視頻,並且他們都進入了前十名(大多數視圖)。我的老闆只想顯示前十名中任何一名成員的前兩名。限制SQL中列表的數量

如何做到這一點。下面是我使用提取數據的腳本:

SELECT a.MediaID, 
COUNT(a.MediaID) AS TimesViewed 
FROM MediaViewLog a 
INNER JOIN MemberVideo b ON b.MemberVideoID = a.MediaID 
INNER JOIN Member c ON c.MemberID = b.MemberID 
WHERE a.ViewDate BETWEEN '5/25/2013 10:04:23 AM' AND '12/12/2050 11:59:59 PM' 
AND a.MediaType = 'V' 
AND b.CreateDate > '5/25/2013 10:04:23 AM' 
AND c.SBIcon = 'N' 
GROUP BY a.MediaID 

MediaViewLog包含以下數據:

+----------------+---------+-----------+-------------------------+ 
| MediaViewLogID | MediaID | MediaType | ViewDate    | 
+----------------+---------+-----------+-------------------------+ 
| 3336   | 7033 | V   | 2013-05-26 03:36:52.573 | 
+----------------+---------+-----------+-------------------------+ 
| 3337   | 7037 | V   | 2013-05-26 04:22:16.682 | 
+----------------+---------+-----------+-------------------------+ 
| 3338   | 12356 | A   | 2013-05-26 03:36:52.573 | 
+----------------+---------+-----------+-------------------------+ 
| 3339   | 7102 | V   | 2013-05-26 07:12:25.428 | 
+----------------+---------+-----------+-------------------------+ 
| 3340   | 7058 | V   | 2013-05-26 08:02:27.003 | 
+----------------+---------+-----------+-------------------------+ 
| 3341   | 7033 | B   | 2013-05-26 03:36:52.573 | 
+----------------+---------+-----------+-------------------------+ 

每個媒體與會員相關的,在「會員」表。 「成員」是主鍵

任何想法如何,如果有一個以上的任何一個成員,作爲前10

任何幫助部分將不勝感激我只能提取前2。

謝謝!

回答

4

對於這一點,使用row_number()功能:

select t.MediaId, t.TimesViewed 
from (SELECT a.MediaID, c.MemberId, COUNT(a.MediaID) AS TimesViewed, 
      row_number() over (partition by c.MemberId order by count(a.MediaId) desc 
           ) as seqnum 
     FROM MediaViewLog a 
     INNER JOIN MemberVideo b ON b.MemberVideoID = a.MediaID 
     INNER JOIN Member c ON c.MemberID = b.MemberID 
     WHERE a.ViewDate BETWEEN '5/25/2013 10:04:23 AM' AND '12/12/2050 11:59:59 PM' 
     AND a.MediaType = 'V' 
     AND b.CreateDate > '5/25/2013 10:04:23 AM' 
     AND c.SBIcon = 'N' 
     GROUP BY a.MediaID, c.MemberId 
    ) t 
where seqnum <= 2; 

這是假設每個視頻僅由一個部件張貼。也就是說,MediaIda.MediaId, c.MemberId的分組確實是一回事。否則,您將混合來自不同用戶的計數(在視頻的「發佈」一側,而不是查看),並且僅爲每個用戶提取兩個更難。

我也認爲應該有一個top 10在那裏。

+0

我從此代碼中得到錯誤:消息208,級別16,狀態1,行1 無效的對象名稱'MediaViewLog'。 – neojakey

+0

@neojakey。 。 。第一行沒有'MediaViewLog'。我做的唯一的改變是:(1)使你的查詢成爲一個子查詢; (2)添加'row_number()'; (3)將'c.MemberId'添加到'group by'和'select';和(4)添加最後的「where」子句。 –

+0

@ gordon-linoff ...終於得到它的工作..非常感謝您的幫助..! – neojakey