限制SQL中的列表数量

时间:2013-05-27 15:14:08

标签: sql sql-server sql-server-2008 sql-server-2012

我们的仪表板上显示了十大视频列表。有时我们有一个用户发布了6个视频的情况,所有这些视频都进入了前十名(大多数视图)。我的老板只想显示前十名中任何一位成员的前2名。

如何做到这一点。这是我用来提取数据的脚本:

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 |
+----------------+---------+-----------+-------------------------+

每个媒体都与“会员”表中的会员相关联。 “MemberID”是主键

如果有任何成员不止一个,我作为前10名的一部分,我怎么才能提取前2名。

任何帮助都会非常感激。

谢谢!

1 个答案:

答案 0 :(得分: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